在php循环中提交带有多个输入的AJAx表单

时间:2017-06-12 07:57:09

标签: php jquery ajax

我正在尝试学习如何使用Ajax在php循环中提交表单。任何人都可以看到为什么下面的代码不会写入我的数据库?如果我取出它工作的sname部分,但只允许更新一列。在此先感谢您的帮助



<!DOCTYPE html>
<html>
<head>

<?php include 'dbconnection.php';?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script>
// Add the counter id as an argument, which we passed in the code above
function chk(id)
{
    // Append the counter id to the ID to get the correct input
    var name=document.getElementById('name' + id).value;
	var name=document.getElementById('sname' + id).value;
    var dataString='name='+ name + '&sname=' + sname;
    $.ajax({
        type:"post",
        url: "dataInsert2.php",
        data:dataString,
        cache:false,
        success:function(phtml){
            // Instead of using the class to set the message, use the ID,
            // otherwise all elements will get the text. Again, append the counter id.
            $('#msg' + id).html(phtml);
        }

    });
    return false;
}
</script>
</head>

<body>
<?php
$query=mysqli_query($connect,"SELECT distinct first_name from people " );

// Initiate a counter variable
$i = 1;

while ($row=mysqli_fetch_array($query))
{
?>
</br> <?php  echo$row["first_name"];   ?>

<form>
<!-- Extra input added here
 Append the counter to the ID -->
<input type="text" id="name<?= $i ?>">
<input type="text" id="sname<?= $i ?>">
<br/>

<!-- Send just the current counter to your method -->
<input type="submit" value="submit"  onclick="return chk('<?= $i ?>')">

</form>
<!-- Append the counter to the message ID -->
<p id="msg<?= $i ?>" class="msg1"></p>
<?php
    // Increment the counter
    $i++;
}

?>
</body>
</html>
&#13;
&#13;
&#13;

dataInsert2.php

&#13;
&#13;
<?php
include 'dbconnection.php';
  $notes = $_POST['name'];
    $class = $_POST['sname'];
 
mysqli_query($connect, "INSERT INTO people(class, notes)
			VALUES ('$class','$notes')");
			
	?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

假设你的php循环在语法和语法上都是正确的,

单击该按钮时,应调用以下函数。

function chk(id)
{
    // Append the counter id to the ID to get the correct input
    var name=document.getElementById('name' + id).value;
    var name=document.getElementById('sname' + id).value;
    var dataString='name='+ name + '&sname=' + sname;
    $.ajax({
        type:"post",
        url: "dataInsert2.php",
        data:dataString,
        cache:false,
        success:function(phtml){
            // Instead of using the class to set the message, use the ID,
            // otherwise all elements will get the text. Again, append the counter id.
            $('#msg' + id).html(phtml);
        }

    });
    return false;
}

在第三行中,在变量声明期间,根据您的逻辑,变量name应该是sname

var sname=document.getElementById('sname' + id).value;

由于在第4行(当您使用它时)找不到该变量,因此它面临错误。因此,该行之后的代码将不会被执行。

相关问题