Survey details won't go through using php, ajax, Mysql

Joined
Oct 26, 2023
Messages
1
Reaction score
0
Hey guys, I'm new here. I was working on a school project about making a survey for a company. But I'm stuck. I made all the questions to be dynamically taken from the database and come with an answer part in form of an input.Clients table. So theres' my survey.php file code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" href="Sondage.css">
<script src="https://kit.fontawesome.com/0000000000.js" crossorigin="anonymous"></script>
<title>Survey UbiPharm Cameroon</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">
<img src="images/Ubipharm Cameroun.png" alt="Company Logo" class="logo">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div id="content">
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="Survey.php">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="Comments.php">Comments</a>
</li>
<li class="nav-item">
<a class="nav-link" href="help.html">Help</a>
</li>
<li class="nav-item">
<a class="nav-link" href="LogoutClients.php">Logout</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
<div class="container">
<h1>Customer Satisfaction Survey</h1>
<form id="survey-form" method="Post">
<div class="question">
<label for="clientName">Client Name:</label>
<input type="text" id="clientName" name="clientName" class="clientType" required>
</div>
<div class="rating-container2">
<input type="checkbox" class="checkbox" id="clientTypePharmacy" name="clientType" value="1">
<label for="clientTypePharmacy">Pharmacy</label>
<input type="checkbox" class="checkbox" id="clientTypeClinic" name="clientType" value="0">
<label for="clientTypeClinic">Clinic</label>
<input type="checkbox" class="checkbox" id="clientTypeSubDistributor" name="clientType" value="2">
<label for="clientTypeSubDistributor">Sub-distributor</label>
</div>
<script>
document.querySelectorAll('.checkbox').forEach(el => el.addEventListener('change', function () {
document.querySelectorAll('.checkbox').forEach(otherEl => {
if (otherEl !== el) otherEl.checked = false;
});
}));
</script>
<?php
$servername = "localhost"; // your host name
$username = "root"; // your database username
$password = ""; // your database password
$dbname = "second_ubipharm"; // your database name
// Create a new mysqli object for database connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sql query to fetch all questions with their id_sondage as 1
$sql = "SELECT * FROM sondage_questions WHERE id_sondage = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data for each row
while($row = $result->fetch_assoc()) {
?>
<form id="survey-form" method="post">
<div class="question">
<label for="q<?=$row['Question_id']?>" name="Quest"><?=$row['Question_id']?>. <?=$row['Question_body']?></label>
<div class="rating-container">
<select id="q<?=$row['Question_id']?>" name="q<?=$row['Question_id']?>rating" aria-describedby="q<?=$row['Question_id']?>ratingHelp" required>
<option selected disabled value="">Select rating</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
</div>
<?php
}
} else {
echo "No more questions.";
}
$conn->close();
?>
<div class="comment-box">
<label for="comment">Additional comments or suggestions:</label>
<textarea id="comment" name="comment" placeholder="Enter your comment" maxlength="255"></textarea>
<p id="charCount">0 / 255 characters</p>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$("#survey-form").submit(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_survey.php", // Replace with the actual file name
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function(response) {
if (response.status === "success") {
// Handle success case
window.location.href = "thankyou.php"; // Redirect to thankyou.php
} else if (response.status === "error") {
// Handle error case
showErrorMessage("Error occurred while submitting the survey!");
}
},
error: function() {
// Handle error case
showErrorMessage("Error occurred while submitting the survey!");
}
});
});
function showErrorMessage(message) {
var toast = '<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 0; right: 0;">' +
'<div class="toast-header">' +
'<strong class="mr-auto">Error</strong>' +
'<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">' +
'<span aria-hidden="true">&times;</span>' +
'</button>' +
'</div>' +
'<div class="toast-body">' +
message +
'</div>' +
'</div>';
$('#content').prepend(toast);
$('.toast').toast({ autohide: false }).toast('show');
}
});
</script>
<style>
.rating-container2 {
display: flex;
align-items: center;
gap: 10px;
}
.checkbox {
display: none;
}
.checkbox + label {
position: relative;
padding: 10px;
border-radius: 10px;
background-color: #f5f5f5;
cursor: pointer;
}
.checkbox + label:before {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #f5f5f5;
box-shadow: 3px 3px 6px #d9d9d9, -3px -3px 6px #ffffff;
transition: 0.3s;
}
.checkbox:checked + label:before {
background-color: #51D78E;
box-shadow: none;
}
.checkbox + label:after {
content: "";
position: absolute;
top: 7px;
left: 7px;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #f5f5f5;
transition: 0.3s;
}
.checkbox:checked + label:after {
background-color: #ffffff;
transform: translateX(10px);
}
</style>
</body>
</html>
Using an ajax_survey.php file:
<?php
$servername = "localhost"; // your host name
$username = "root"; // your database username
$password = ""; // your database password
$dbname = "second_ubipharm"; // your database name
// Create a new mysqli object for database connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the client name and type
$clientName = $_POST['clientName'];
$clientType = $_POST['clientType'];
// Insert the client data into the clients table
$insertClientSql = "INSERT INTO answers (nom_client, client_type) VALUES (?, ?)";
$stmt = $conn->prepare($insertClientSql);
$stmt->bind_param("ss", $clientName, $clientType);
if ($stmt->execute()) {
$clientId = $stmt->insert_id;
$stmt->close();
// Get the survey questions
$surveyQuestionsSql = "SELECT question_body FROM sondage_questions WHERE id_sondage = 1;";
$surveyQuestionsResult = $conn->query($surveyQuestionsSql);
if ($surveyQuestionsResult->num_rows > 0) {
while ($row = $surveyQuestionsResult->fetch_assoc()) {
$questionId = $row['Question_id'];
$questionBody = $row['Question_body'];
$answerRating = $_POST['q' . $questionId . 'rating'];
// Insert the answer into the answers table
$insertAnswerSql = "INSERT INTO answers (id_client, question_id, question_body, answer, comment) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($insertAnswerSql);
$stmt->bind_param("iisi", $clientId, $questionId, $questionBody, $answerRating $comment);
$stmt->execute();
$stmt->close();
}
}
// Get the comment
$comment = $_POST['comment'];
// Calculate the average rating for the client
$averageRatingSql = "SELECT AVG(answer) AS average_rating FROM answers WHERE client_id = ?";
$stmt = $conn->prepare($averageRatingSql);
$stmt->bind_param("i", $clientId);
$stmt->execute();
$averageRatingResult = $stmt->get_result();
$averageRatingRow = $averageRatingResult->fetch_assoc();
$averageRating = $averageRatingRow['average_rating'];
$stmt->close();
// Update the client's average rating
$updateClientSql = "UPDATE clients SET average_rating = ? WHERE client_id = ?";
$stmt = $conn->prepare($updateClientSql);
$stmt->bind_param("di", $averageRating, $clientId);
$stmt->execute();
$stmt->close();
// Calculate the overall average rating
$overallAverageRatingSql = "SELECT AVG(average_rating) AS overall_average_rating FROM clients";
$overallAverageRatingResult = $conn->query($overallAverageRatingSql);
$overallAverageRatingRow = $overallAverageRatingResult->fetch_assoc();
$overallAverageRating = $overallAverageRatingRow['overall_average_rating'];
// Update the overall average rating
$updateOverallAverageSql = "UPDATE results SET average_rating = ?";
$stmt = $conn->prepare($updateOverallAverageSql);
$stmt->bind_param("d", $overallAverageRating);
$stmt->execute();
$stmt->close();
// Send the response
$response = array("status" => "success");



Sorry if i'm not posting correctly, it's my first time asking for help online. I've been struggling for the past weeks. Thank you for your help and have a great day!
echo json_encode($response);
} else {
// Send the error response
$response = array("status" => "error");
echo json_encode($response);
}
} else {
// Send the response for invalid request
$response = array("status" => "error");
echo json_encode($response);
}
$conn->close();
?>
ScreenShot_20231026021249.png
ScreenShot_20231026021350.png

ScreenShot_20231026021232.png
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,152
Members
46,697
Latest member
AugustNabo

Latest Threads

Top