如何使用AJAX提交表单

时间:2014-01-18 07:24:50

标签: php jquery ajax

我有一个测验网站。我想重新设计我的问题表单以提交用户通过AJAX给出的答案,验证服务器上的答案并显示结果以及用户的下一个答案。 请指导我如何做到这一点。我已经使用的代码是:

<?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>

4 个答案:

答案 0 :(得分:2)

你可以用以下结构来做到这一点;

首先将$ad变量放在表单中的隐藏元素中;

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

然后

$.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");
    }
  }
});

使用表单变量和问题ID检查表单结果,并在服务器端返回结果

答案 1 :(得分:1)

使用此javascript(Jquery代码提交表单)。

// 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.
});

作为回复(数据),您可以提供下一个问题的详细信息。

答案 2 :(得分:1)

尝试这样的事情

$("#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.
});

<强>参考

jQuery Ajax()=&gt; http://api.jquery.com/jquery.ajax/

Serialize()=&gt; http://api.jquery.com/serialize/

jQuery Submit()=&gt; http://api.jquery.com/submit/

jQuery post =&gt; http://api.jquery.com/jquery.post/

示例

  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

答案 3 :(得分:0)

1-设置表格id = general-knowledge-form

2-在头标记上加载jquery lib,如下所示

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

3-创建新的隐藏输入<input type="hidden" id="q_id" value="<?php echo $a; ?>" />

4-为ex创建新的php文件:ajax.php验证用户答案然后返回相应的html outbut,此文件包含以下代码:

<?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-在body标签之前在页面末尾添加以下脚本来处理ajax.php的ajax请求,然后在页面中附加适当的html

        <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>