-1

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>
Hüseyin BABAL
  • 14,821
  • 4
  • 48
  • 70
Ankur Gupta
  • 597
  • 1
  • 6
  • 18

4 Answers4

2

You can do that with following structure;

First put $ad variable in hidden element in your form;

<input type="hidden" name="ad" value="<?php echo $a?>"/>

And then

$.ajax({
  type: "POST",
  url: 'general-knowledge.php',
  data: $(".common form").serialize(),
  success: function(data) {
    if (data.result == true) {
        alert("It is correct");
        window.location = "next_question.html"
    } else {
        alert("Incorrrect result");
    }
  }
});

Check form results by using form variables and question id, and return result on server side

Hüseyin BABAL
  • 14,821
  • 4
  • 48
  • 70
1

Use this javascript (Jquery code to submit you form).

// frm_id is the id of the form
$("#frm_id").submit(function() {
    var url = "path/to/your/script.php"; // the script where you handle the form input and save to database.
    $.ajax({
           type: "POST",
           url: url,
           data: $("#frm_id").serialize(), //serializes the form's elements.
           success: function(data){
               alert(data); // show response from the php script.
           }
         });
    return false; // prevent to execute the actual submit of the form.
});

In response (data) you can bring details of next question.

Ravi
  • 3,308
  • 4
  • 29
  • 50
1

try something like this

$("#form_id").submit(function() {
    $.ajax({
           type: "POST",
           url: this.action,
           data: $(this).serialize(), //Serialize a form to a query string.
           success: function(response){
               alert(response); //response from server.
           }
         });
    return false; // prevent form to submit.
});

Reference

jQuery Ajax() => http://api.jquery.com/jquery.ajax/

Serialize() => http://api.jquery.com/serialize/

jQuery Submit() => http://api.jquery.com/submit/

jQuery post => http://api.jquery.com/jquery.post/

Example

  1. http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/

  2. Submitting HTML form using Jquery AJAX

  3. http://hayageek.com/jquery-ajax-form-submit/

  4. http://www.phpeveryday.com/articles/jQuery-AJAX-Form-Submission-P973.html

Community
  • 1
  • 1
rajesh kakawat
  • 10,330
  • 1
  • 18
  • 38
0

1- Set form id = general-knowledge-form

2- load jquery lib on your head tag as following

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

3- create new hidden input <input type="hidden" id="q_id" value="<?php echo $a; ?>" />

4- create new php file for ex: ajax.php to verify user answer then return the appropriate html outbut this file contain the following code:

<?php
mysql_connect('localhost', 'root', 'root');
mysql_select_db('test');

$a = filter_var($_POST['q_id'], FILTER_SANITIZE_NUMBER_INT);
$ans = filter_var($_POST['ans'], FILTER_SANITIZE_STRING);

$q1 = "select * from question WHERE q_id=" . $a;
$rw = mysql_query($q1);
$row = mysql_fetch_object($rw);
?>

<?php if ($ans == $row->true_ans): ?>
    <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 $row->true_ans; ?>'</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 endif;

5- add the following script on end of your page before body tag to handle your ajax request to ajax.php, then append appropriate html to your page

        <script>
        $(document).ready(function() {
            $("#general-knowledge-form").submit(function(event) {
                var ans = $('input[name=ans]:checked').val();

                if (ans !== undefined) {
                    var q_id = $("#q_id").val();
                    $.ajax({
                        type: "POST",
                        url: "ajax.php",
                        data: {q_id: q_id, ans: ans}
                    })
                            .done(function(html) {
                                $("#resultdisplay").empty();
                                $("#resultdisplay").append(html);
                            });

                } else {
                    alert('Plz select your answer.');
                }

                event.preventDefault();
            });
        });
    </script>