I have a quiz website. I want to redesign my question form to submit the answer given by the user through AJAX, verify the answer on the server and display the result along with the next answer to the user. Please guide me how to do this. The codes I am already using are:
<?php
$a = $_REQUEST['ad'];
include("connection.php");
if (isset($_REQUEST['ad']))
{
if ($_REQUEST['ad'] == $a)
{
$q1 = "select * from question WHERE q_id= '$a' AND cat_id='General Knowledge'";
$rw = mysql_query($q1);
if ($row = mysql_fetch_assoc($rw))
{
if ($a % 10 == 0) {
$qno = 10;
} else {
$qno = substr($a, -1, 1);
}
?>
<b><?php echo "Q" . $qno . ". ";
echo $row['q_desc']; ?></b><br/><br/>
<div class="quizimage">
<img src="images/<?php echo $a; ?>.jpg" alt="General Knowledge Quiz"/>
</div>
<font class="common">
<table align="center">
<form action="general-knowledge.php?ad=<?php echo $a; ?>" method="post">
<tr align="center">
<input type="radio" name="ans"
value="<?php echo $row['ans1']; ?>" <?php echo($_POST['ans'] == $row['ans1'] ? 'checked' : '') ?>/>
<?php echo $row['ans1']; ?>
<br/>
<input type="radio" name="ans"
value="<?php echo $row['ans2']; ?>" <?php echo($_POST['ans'] == $row['ans2'] ? 'checked' : '') ?>/>
<?php echo $row['ans2']; ?><br/>
<input type="radio" name="ans"
value="<?php echo $row['ans3']; ?>" <?php echo($_POST['ans'] == $row['ans3'] ? 'checked' : '') ?>/>
<?php echo $row['ans3']; ?><br/>
<input type="radio" name="ans"
value="<?php echo $row['ans4']; ?>" <?php echo($_POST['ans'] == $row['ans4'] ? 'checked' : '') ?>/>
<?php echo $row['ans4']; ?><br/>
</font>
<tr>
<td><input type=submit name=sub value=Submit_Answer></td>
</tr></form></table>
<table border="1" align="center">
<div class="adunit3">
<?php
include "adunit3.php";
?>
</div>
<?php
}
$_SESSION['quiz_visited'] = $a;
if (isset($_POST['sub'])) {
$a_value = $a;
$answer = $_POST['ans'];
$q2 = "select * from question where q_id=$a_value";
$r2 = mysql_query($q2);
if ($row = mysql_fetch_array($r2))
$trueans = $row['true_ans'];
if ($answer == $trueans) {
$score = $_SESSION['score'];
$score = ++$score;
$_SESSION['score'] = $score;
?>
<div class="resultdisplay">
Your answer is correct. <h3>General Knowledge Trivia</h3><?php echo $row['trivia']; ?> <br/> <?php
if ($a % 10 == 0) {
$a = ++$a;
?>
<b>Click <a href="general-knowledge.php?ad=<?php echo $a; ?>">Here</a> to view your result.</b>
<?php
} else {
$a = ++$a;
?>
<b>Click <a href="general-knowledge.php?ad=<?php echo $a; ?>">Here</a> for next question.</b>
<?php
}
?>
</div>
<?php
} else {
?>
<div class="resultdisplay">
Your answer is wrong. The correct answer is <i>'<?php echo $trueans; ?>'</i>.
<h3>General Knowledge Trivia</h3><?php echo $row['trivia']; ?> <br/>
<?php $a = ++$a; ?>
<b>Click <a href="general-knowledge.php?ad=<?php echo $a; ?>">Here</a> for next question.</b>
</div>
<?php
}
}
++$a;
$a = ++$a;
}
}
?>
</table>