I am building a quiz and what i am doing now is working on taking the user's input and checking the user's submission with an answers table in my database and return the user the score.
My quiz is in the form of multiple choice for users to select, and each option carries its own value. What i have done to capture the data is to serialize the form data and store all of the form's data in a object. The object looks something like this:
{ question1: '1', question2: '2', question3: '3', question4: '4', question5: '5' }
So it sorts of stores the question and user answer as a key value pair, with the question number coming first, and the user selected option coming next. As you can see from the code below, i am using an .each to take out the key value pairs, and what im thinking of doing is everytime the .each runs, to run an ajax command to an external checkanswer.php script to verify the user's chosen option. Everytime the server returns a match, the php returns a text string "correct" to the ajax, which then increments 1 to a created count variable. I have also appended the php script below. With @barmar's advice, i have removed json entirely, but the count variable under .each stil isnt giving the correct number based on the number of correct answers returned from the ajax call. ++ Upon reading up more about the way ajax works, it seems like ajax does not wait for the submit handler and therefore i must change the code. One way is to actually send the entire string across and for php to loop through the key value pairs and do the counting there and return the value to ajax. What do you all think?
<script>
$('#quizform').submit(function() {
var data = $(this).serializeArray();
count = 0;
$.each(data, function(i, el) {
//display the key and value pair
var k = el.name;
var v = el.value;
var request = $.ajax({
url: "checkanswer.php",
type: "POST",
data:{ k:k, v:v},
dataType:"text",
success: function(data) {
if (data=="correct") {
count++;
}
},
error: function(request, err){
alert(err);
}
});
});
alert(count);
return false;
});
</script>
The PHP script:
<?php
session_start();
include_once("config.php");
if (isset($_POST['k']) && isset($_POST['v'])){
$questionid=$_POST['k'];
$option=$_POST['v'];
$result=mysqli_query($mysqli, "SELECT COUNT(*) FROM answer WHERE question_id = ".$questionid." AND optionid = ".$option."");
if($result==0) {
echo"wrong";
}else if ($result == 1) {
echo"correct";
}
}
?>
I have edited the code above