0

I made an online quiz that takes questions stored in a php database and displays them via jQuery's post method. The user can go to the next question or back to the previous one. I would like to store the user's answers so that at the end I can calculate the right and wrong answers and display the questions the user got wrong. I would like to store the user's answers in jQuery somehow and not in a php database. What would be the best way to go about this? Thanks in advance.

HTML and jQuery

<script>
$(document).ready(function() {
var number = 0;  //this is the current # of the question the user is working on
$('#next').click(function() {
number = number +1;

    if (number > 1){
$('#prev').css('display','block');
}

    $.post('getquestions.php', {number: number}, function(result){

        $('#questionArea').html(result);
    });

});

$('#prev').click(function() {
number = number -1;
    if (number < 2){
$('#prev').css('display','none');
}
    $.post('getquestions.php', {number: number}, function(result){

        $('#questionArea').html(result);
    }); 
});
});
</script>

<div id='questionArea'></div>

<input type='button'  id='prev' value='previous' style='display: none;'/>
<input type='button'  id='next' value='next' />

getquestions.php file:

<?php

    require '../connect.php';
  $question_number = $_POST['number'];

$sql="SELECT * FROM questions WHERE test='1' AND question_number='$question_number' LIMIT 1";
$result=mysqli_query($con,$sql);

while ($row = mysqli_fetch_array($result)) {
$question = $row['question'];
$chA = $row['choiceA'];
$chB = $row['choiceB'];
$chC = $row['choiceC'];
$chD = $row['choiceD'];
$chE = $row['choiceE'];
$qid = $row['qid'];
$correct = $row['correct'];
}



echo "<div id='question'>" . $question . "</div>";
echo "<input type='radio' name='a' value=" . $chA ."> " . $chA . "<br>";
echo "<input type='radio' name='b' value=" . $chB ."> " . $chB . "<br>";
echo "<input type='radio' name='c' value=" . $chC ."> " . $chC . "<br>";
echo "<input type='radio' name='d' value=" . $chD ."> " . $chD . "<br>";
echo "<input type='radio' name='e' value=" . $chE ."> " . $chE . "<br>";
?>
marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
user176105
  • 181
  • 1
  • 2
  • 18

4 Answers4

0

Two alternatives:

  1. post all previous answers to next page during submit form and retrieve them at last page.
  2. store data in cookie and retrieve cookie data at last page (not works when cookies is disabled.)
Ali Sheikhpour
  • 8,724
  • 4
  • 29
  • 66
  • with your first alternative, if a user clicks and answer choice and then clicks the "previous" button to go back and then the "next" button to go forward the radio choice is lost. – user176105 Mar 29 '15 at 23:57
  • Hide previous answers in a hidden field not in visible radio buttons. – Ali Sheikhpour Mar 30 '15 at 07:33
0
  1. You can use jquery or javascript to use and store values in cookies. Read here.

  2. You can use hidden fields in your html itself to store the user values and then read them later.

  3. You could also use jquery to store data. Read here.

Community
  • 1
  • 1
Rash
  • 6,184
  • 1
  • 42
  • 58
0

Try utilizing .data() ; store, retrieve results in array at #questionArea .data().

Before #next , #prev click events defined

$(document).ready(function() {
    $("#questionArea").data("results", []);
    var number = 0;
    // `#next` , `#prev` `click` events
})

at $.post()

$.post("getquestions.php", {number: number}, function(result){    
    $("#questionArea").html(result).data("results").push(results);
}); 
guest271314
  • 1
  • 10
  • 82
  • 156
0

I would use localStorage for this. Here is a contrived example of what that might look like:

Here is a working jsFiddle demo

At the end of the quiz, you'll end up with the following:

{"1560":"d","1909":"c","2186":"a","3565":"b","3817":"e"}

Where the keys are the row ids for each question from your database and their values are the user's selected answer.

HTML

Answer 5 questions and your results will be shown to you:<br><br><br>
<div id="container"></div><br>
<input type="button" id="answerQuestion" value="Submit Answer"/>

Javascript

localStorage.setItem('quizprogress','');
var questionsAsked=[]; 

// I know you're loading your questions via php, this is just an example 
function loadQuestion(){
    if(questionsAsked.length< 5){ // this just limits the demo to six questions
        var rowId = randomIntFromInterval(1025,5021);// just getting a random number here, you should use the row id from your database here
        var fakeQuestion = '<div id="question" data-qestion-id="'+rowId+'">Question '+rowId+'</div>'+  // adding in the row id as a data attribute here give us something to track it by
                           '<input type="radio" name="answer" value="a" class="answer">a<br>'+
                           '<input type="radio" name="answer" value="b" class="answer">b<br>'+
                           '<input type="radio" name="answer" value="c" class="answer">c<br>'+
                           '<input type="radio" name="answer" value="d" class="answer">d<br>'+
                           '<input type="radio" name="answer" value="e" class="answer">e<br>';
       questionsAsked.push(rowId);    
       $('#container').html(fakeQuestion);
    }
    else{ // had our six questions, lets look at our answers now
        // when the quiz is done, localstorage `quizprogress` will contain all of our question ids with thier respective answer choice
        $('#container').html('');
        var quizprogress = JSON.parse(localStorage.getItem('quizprogress'));
        $.each(questionsAsked, function(i,qId){
            $('#container').append('Question '+qId+': '+quizprogress[qId]+'<br>');
        });
        // clean up localStorage
        localStorage.removeItem('quizprogress');
    }

}
// load the first question for the demo
loadQuestion();

// listen for change of answer (or submit button etc....)
$('#answerQuestion').click(function(){
    // you'll want some check here to be sure an answer was selected
    // get quizprogress from localstorage
    var quizprogress = localStorage.getItem('quizprogress');
     // if we  have some answers stored already, load the current quizprogress object, or load a new object if we just started
    quizprogress = quizprogress=='' ? {} : JSON.parse(quizprogress);
    // get the database row id from the current question
    var qId = $('#question').data('qestion-id');
    quizprogress[qId] = $('input[name=answer]:checked').val();
    // Put the object back into storage
    localStorage.setItem('quizprogress', JSON.stringify(quizprogress));
    // load the next question for the demo
    loadQuestion();
});

// random numbers, just for the demo, you dont need this
function randomIntFromInterval(min,max){
    return Math.floor(Math.random()*(max-min+1)+min);
}
Wesley Smith
  • 17,890
  • 15
  • 70
  • 121