Search the Community
Showing results for tags 'quiz json'.
-
I got some code to make a simple quiz, but I'm struggling to get it to work. I think the form and the following JavaScript code are set up correctly, but I'm running into problems with the PHP code at the end. I'm especially confused by the JSON reference at the very end; I don't have a clue what it means or what do do with it. Does anyone know how to fix/complete this script? On another note, why is it necessary to use JSON in the first place? Aren't the answers already provided in the PHP code (e.g. $answer1 = $_POST['A']? Thanks. <form action=""> <fieldset> What color is an apple? <label>blue <input type="radio" value="A" name="question-1"></label> <label>red <input type="radio" value="B" name="question-1"></label> <label>yellow <input type="radio" value="C" name="question-1"></label> <label>gray <input type="radio" value="D" name="question-1"></label> </fieldset> <fieldset> What color is a banana? <label>yellow <input type="radio" value="A" name="question-2"></label> <label>blue <input type="radio" value="B" name="question-2"></label> <label>red <input type="radio" value="C" name="question-2"></label> <label>gray <input type="radio" value="D" name="question-2"></label> </fieldset> <fieldset> What color is the sky? <label>yellow <input type="radio" value="A" name="question-3"></label> <label>blue <input type="radio" value="B" name="question-3"></label> <label>red <input type="radio" value="C" name="question-3"></label> <label>gray <input type="radio" value="D" name="question-3"></label> </fieldset> <fieldset> What color is snow? <label>white <input type="radio" value="A" name="question-4"></label> <label>blue <input type="radio" value="B" name="question-4"></label> <label>red <input type="radio" value="C" name="question-4"></label> <label>gray <input type="radio" value="D" name="question-4"></label> </fieldset> <input type="button" value="Submit" class="submit" id="Submit2"> </form> <script> $(function(){ // Trap the form submit event $('form').submit(function(e){ e.preventDefault() // Prevent browser refresh var answers = $(this).seralize() // Manually send the data with AJAX $.post({ url: $(this).attr('action'), data: answers, // Stuff to do after we get a response success: function(response){ $('#results').text(response.correct) } }) }) }) </script> <?php $answer1 = $_POST['A']; $answer2 = $_POST['A']; $answer3 = $_POST['C']; $answer4 = $_POST['D']; $totalCorrect = 0; if ($answer1 == "B") { $totalCorrect++; } if ($answer2 == "A") { $totalCorrect++; } if ($answer3 == "B") { $totalCorrect++; } if ($answer4) { $totalCorrect++; } // Send the data back as JSON die json_encode(array( 'correct' => $totalCorrect; )); ?>