繁体   English   中英

无法使用ajax提交表单数据?

[英]unable to submit form data using ajax?

我对php很陌生,不了解javascript,已经使用tutorials完成了所有js工作。还尝试使用stackoverflow的现有解决方案,但没有成功!

我想做的是尝试基于“选择选项”调用的值使用“提交”按钮更新数据库值。

问题是我单击提交按钮(在viewtest.php上)后,数据库中没有数据正在更新,我也试图添加'update.php'来形成动作。

这是viewtest.php的屏幕截图 在此处输入图片说明

这是我的代码:

viewtest.php

<form method="POST" action="">
    <table border="1px"><tr> <td>
<select required name="tstname" id="test" onChange="fetch_ques()">
<option> Select Test Name</option>
<?php
$res=mysqli_query($connection,"select * from test_detail");
while($row=mysqli_fetch_array($res))
    {
    ?>
    <option value="<?php echo $row["test_name"]; ?>"> 
<?php echo 
$row["test_name"]; echo' - - ['. $row['test_category'].']'; ?> </option>

    <?php
            }
    ?>
    </select>
    </div>

<td>    
<div id="qnos"><select></select></div></td></tr>

<tr><td colspan="2" align="center">
 <input type="submit" name="btnSubmit" id="vform" value="Update Question"> </td></tr>
</form>
</table>
<div id="ques"></div>

<script type="text/javascript">
function fetch_ques()
 {
 var xmlhttp=new XMLHttpRequest();
 xmlhttp.open("GET","getq.php?
 tstnm="+document.getElementById("test").value,false); // function id
 xmlhttp.send(null);
 document.getElementById("qnos").innerHTML=xmlhttp.responseText;  // div id
 }

 function display_ques()
 {
 var xmlhttp=new XMLHttpRequest();
 xmlhttp.open("GET","displayq.php?
qnos="+document.getElementById("quesdd").value,false);
 xmlhttp.send(null);
 document.getElementById("ques").innerHTML=xmlhttp.responseText;
 }

   </script>

   <script type="text/javascript">
   $(document).ready(function()
   {
   $("#vform").submit(); (function()
   // document.getElementById("vform").submit();(function()
   {
   location.href='update.php?

qno='+$("#quesno").val()+'&qn='+$("#ques").val()+'&c1='+$("#a1").val()+'&c2='+$
 ("#a2").val()+'&c3'+$("#a3").val()+'&c4='+$("#a4").val()+'&cr='+$("#cr").val();
       });
       });
       </script>


   <?php 
   if(isset($_GET['st']) && $_GET['st'] !== "")
    {
    echo"updated";      
    }
    else echo "Error: ".mysqli_errno();
    ?>

displayq.php //用于在选择菜单中获取数据

 <?php
 include '../connect.php';
 $quesno=$_GET["qnos"];

 if($quesno!="")
 {
 $qry=mysqli_query($connection,"select * from quesadd where quesid='$quesno'");

echo "<table name='ques'>";
while($ftc=mysqli_fetch_array($qry))
{ 
?>

 <form method="POST" action="">
 <table name="ques">
 <tr><td align="center" colspan="2"> <!-- // Comment <input type="submit" name="submit" id="upq" value="Update Question">--></td> </tr>
 <tr> <td align="center"> <b> Question : <input type="text" id="quesno" value="<?php echo $ftc["quesid"];?>" disabled></b></td> 
 <td> <textarea name="ques" id="ques" cols="100" rows="3" placeholder="Please Input The Question Here !"> <?php echo $ftc['ques'];?></textarea> </td> </tr>
 <tr> <td width="25%" align="center" colspan="2"> <br> <b>Choices</b> </td> </tr>
 <tr> <td align="center" colspan="2"><b>1.</b> <input type="text" id="a1" name="a1" value="<?php echo $ftc['c1'];?>"> </td> </tr>
 <tr> <td align="center" colspan="2"><b>2.</b> <input type="text" id="a2" size="20px" name="a2" value="<?php echo $ftc['c2'];?>"> </td> </tr>
 <tr> <td align="center" colspan="2"><b>3.</b> <input type="text" id="a3" size="20px" name="a3" value="<?php echo $ftc['c3'];?>"> </td> </tr>
 <tr> <td align="center" colspan="2"><b>4.</b> <input type="text" id="a4" size="20px" name="a4" value="<?php echo $ftc['c4'];?>"> </td> </tr>
 <tr> <td align="center" colspan="2"><b><font color="maroon">Correct Answer</font></b> <input type="text" size="20px" id="cr" name="correct" value="<?php echo $ftc['answer'];?>"> </td> </tr>

</table>
</form>
 <?php
 }
 echo "</table>";
 }
 ?>

 </tr> </td> 
 </table>
 </form>

update.php //用于通过从“ viewtest.php”获取值来更新问题

<?php
include '../connect.php';
$qn=$_GET['qno'];
$qname=$GET['qn'];
$a1=$GET['c1'];
$a2=$GET['c2'];
$a3=$GET['c3'];
$a4=$GET['c4'];
$acr=$GET['cr'];

 $update=mysqli_query($connection,"update quesadd SET ques='$qname', 
c1='$a1',c2='$a2',c3='$a3',c4='$a4',answer='$acr' where quesid='$qn' ");
 if($update==true)
 {

    header('location:viewtest.php?st=true');
 }
?>

我可以看到多个问题,不知道所有问题是否都会解决,但会有所帮助。

$("#vform").submit(); (function()

上面的行指出,如果已提交id="vform"<form> ,请执行此功能。 您的表单没有ID,因此它将永远不会触发。 另一个问题是该功能不是触发器的一部分。 应该是这样的

$("#vform").submit(function()

完整的代码如下所示:

       <script type="text/javascript">
           $(document).ready(function(){
               $("#vform").submit(function(e){
                   e.preventDefault();
                   location.href='update.php?qno='+$("#quesno").val()+'&qn='+$("#ques").val()+'&c1='+$("#a1").val()+'&c2='+$("#a2").val()+'&c3'+$("#a3").val()+'&c4='+$("#a4").val()+'&cr='+$("#cr").val();
                   return false;
               });
           });
       </script>

使用AJAX提交表单并使用javascript刷新/重定向页面。

viewtest.php

<?php
include '../connect.php';
?>
<form method="POST" action="">
    <table border="1px">
        <tr>
            <td>
                <select required name="tstname" onchange="display_ques()" id="test">
                    <option> Select Test Name</option>
                    <?php
                    $res = mysqli_query($connection, "select * from test_detail");
                    while ($row = mysqli_fetch_array($res)) {
                        ?>
                        <option value="<?php echo $row["test_id"]; ?>">
                            <?php echo
                            $row["test_name"];
                            echo ' - - [' . $row['test_category'] . ']'; ?> </option>

                        <?php
                    }
                    ?>
                </select>
            </td>
            <td>
                <div id="qnos">
                    <select>
                        <!-- put code here for showing question id/number -->
                    </select></div>
            </td>
        </tr>

        <tr>
            <td colspan="2" align="center">
                <input type="submit" name="btnSubmit" id="vform" value="Update Question"></td>
        </tr>
    </table>
</form>
<div id="ques"></div>
<h1 id="status"></h1>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
    function display_ques() {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("ques").innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("GET", "displayq.php?qnos=" + document.getElementById("test").value, true);
        xmlhttp.send(null);
    }

    function fetch_ques() {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "getq.php?tstnm = " + document.getElementById("test").value, false); // function id
        xmlhttp.send(null);
        document.getElementById("qnos").innerHTML = xmlhttp.responseText;  // div id
    }

    $(document).ready(function () {
        $('#vform').on('click', function (e) {
            e.preventDefault();
            var data = $('form#update').serialize();
            $.post('update.php', data, function (response) {
                // response is the data returned from php echo json_encode(['results' => true/false]), from update.php
                var res = JSON.parse(response);
                if (res.results == true) {
                    $('#status').html('Data was updated');
                } else {
                    $('#status').html('Error occured while trying to update data.');
                    console.log(response);
                }
            });
        });
    });
</script>

我已经给出了您的formid ,以便能够使用jQuery对其进行序列化,并且还添加了一个隐藏的输入来保存当前问题的ID。

displayq.php

<?php
include '../connect.php';
$quesno = $_GET["qnos"];

if($quesno != "") : ?>
    <form id="update" method="POST" action=""> <!-- added an id to the form -->
        <table name="ques">
    <?php
    $qry = mysqli_query($connection,"select * from quesadd where quesid='$quesno'");
    while($ftc = mysqli_fetch_array($qry)) : ?>

                <tr><td align="center" colspan="2"> <!-- // Comment <input type="submit" name="submit" id="upq" value="Update Question">--></td> </tr>
                <tr> <td align="center"> <b> Question : <input type="text" id="quesno" value="<?php echo $ftc["quesid"];?>" disabled></b></td>
                    <td> <textarea name="ques" id="ques" cols="100" rows="3" placeholder="Please Input The Question Here !"> <?php echo $ftc['ques'];?></textarea> </td> </tr>
                <!-- added this hidden input to hold the question number -->
                <input type="text" id="quesno" name="quesno" value="<?php echo $ftc["quesid"];?>" hidden>
                <tr> <td width="25%" align="center" colspan="2"> <br> <b>Choices</b> </td> </tr>
                <tr> <td align="center" colspan="2"><b>1.</b> <input type="text" id="a1" name="a1" value="<?php echo $ftc['c1'];?>"> </td> </tr>
                <tr> <td align="center" colspan="2"><b>2.</b> <input type="text" id="a2" size="20px" name="a2" value="<?php echo $ftc['c2'];?>"> </td> </tr>
                <tr> <td align="center" colspan="2"><b>3.</b> <input type="text" id="a3" size="20px" name="a3" value="<?php echo $ftc['c3'];?>"> </td> </tr>
                <tr> <td align="center" colspan="2"><b>4.</b> <input type="text" id="a4" size="20px" name="a4" value="<?php echo $ftc['c4'];?>"> </td> </tr>
                <tr> <td align="center" colspan="2"><b><font color="maroon">Correct Answer</font></b> <input type="text" size="20px" id="cr" name="correct" value="<?php echo $ftc['answer'];?>"> </td> </tr>

  <?php endwhile; ?>
        </table>
    </form>
<?php endif; ?>

然后在update.php您可以使用$_POST访问值

<?php

include '../connect.php';

$qn = trim($_POST['quesno']);
$qname = trim($_POST['ques']);
$a1 = trim($_POST['a1']);
$a2 = trim($_POST['a2']);
$a3 = trim($_POST['a3']);
$a4 = trim($_POST['a4']);
$acr = trim($_POST['correct']);

$sql  = "update quesadd SET ques='$qname', c1='$a1',c2='$a2',c3='$a3',c4='$a4',answer='$acr' where quesid='$qn'";
if (mysqli_query($connection, $sql)) {
    // returning data to jQuery, as response
    // jQuery will parse this as json {results: true}
    echo json_encode(['results' => true]);
} else {
    // returning data to jQuery, as response
    // jQuery will parse this as json {results: false}
    echo json_encode(['results' => false]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM