在php循环中提交AJAx表单

时间:2017-06-10 16:19:05

标签: php jquery ajax

我一直在寻找3周,似乎无法解决这个问题。我是Ajax的新手,但已经想出如何使用它来提交单个表单。我试图学习如何使用Ajax在php循环中提交表单。我认为它与个人身份有关,但我不确定如何创建它们。我的编程只允许我提交第一个表格。有人知道如何解决这个问题所以我可以在循环中提交表单吗?非常感谢您的帮助

到目前为止,这是我的代码



<!DOCTYPE html>
<html>
<head>

<?php include 'dbconnection.php';?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function chk()
{
	var name=document.getElementById('name').value;
	var dataString='name='+ name;
	$.ajax({
		type:"post",
		url: "dataInsert.php",
		data:dataString,
		cache:false,
		success:function(phtml){
			$('.msg1').html(phtml);
		}
		
	});
	return false;
}

</script>

</head>
<body>
<?php
$query=mysqli_query($connect,"SELECT distinct first_name from people " );
while ($row=mysqli_fetch_array($query))
{
?>
</br> <?php  echo$row["first_name"];   ?>

<form>
<input type="text" id="name">
<br/>
<input type="submit" value="submit"  onclick="return chk()">

</form>
<p id="msg" class="msg1"></p>
<?php
}

?>
</body>

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

dataInsert.php

&#13;
&#13;
<?php
$name=$_POST['name'];
echo "Response: ".$name;
?>



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

任何帮助都会非常感激

1 个答案:

答案 0 :(得分:0)

由于ID必须在HTML文档中是唯一的,因此您需要为每个字段指定不同的ID。这适用于元素上的所有 id(例如msg)当完成后,您可以将该id传递给您的方法,使您的js函数可重用。

循环(参见注释以查看更改):

<?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>
<!-- Append the counter to the ID -->
<input type="text" id="name<?= $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++;
}

?>

js-function(再次参见注释以查看更改):

// 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 dataString='name='+ name;
    $.ajax({
        type:"post",
        url: "dataInsert.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;
}

现在你应该能够发送彼此独立的所有表格。