【发布时间】:2017-07-16 04:18:31
【问题描述】:
我在通过 jquery-ajax 将<select> 标记中的status 更改为数据库时遇到了重大问题。
注意:我已经在 stackoverflow 中搜索过这个问题。但那些回答并没有接近我的问题。下面是这些链接 link1、link2、link3
当我单击第一行选择框时,数据通过 ajax 发送,status column in table 得到更新,它也在 mysql 数据库中更新。
But when is select 2nd, 3rd row it doesn't change not update the status column in html page nor in database here is the output image.
提前谢谢你..
HTML 文件:index.php
<?php
include('processing.php');
$newobj = new processing();
?>
<html>
<head>
<title>Jquery Ajax select <tag> with PHP Mysql</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<table border="1">
<tr>
<th>Id</th>
<th>Product name</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php echo $newobj->display();?>
</table>
<script>
$(document).ready(function(){
$("#selectstatus").change(function(){
var statusname = $("#selectstatus").val();
var getid = $("#getid").val();
$.ajax({
type:'POST',
url:'ajaxreceiver.php',
data:{statusname:statusname,getid
:getid},
success:function(result){
$("#display").html(result);
}
});
});
});
</script>
</body>
</html>
Ajax 文件:ajaxreceiver.php
<?php
include('processing.php');
$newobj = new processing();
if(isset($_POST['statusname'],$_POST['getid'])){
$statusid = $_POST['statusname'];
$id = $_POST['getid'];
$newobj->getdata($statusid,$id);
}
?>
PHP 类文件:processing.php
<?php
class processing{
private $link;
function __construct(){
$this->link= new mysqli('localhost','root','','example');
if(mysqli_connect_errno()){
die ("connection failed".mysqli_connect_errno());
}
}
function display(){
$sql = $this->link->stmt_init();
$id=1;
if($sql->prepare("SELECT id,productname,status FROM ajaxselect")){
$sql->bind_result($id,$productname,$status);
if($sql->execute()){
while($sql->fetch()){
?>
<tr>
<td><input type="hidden" id="getid" value="<?php echo $id;?>"><?php echo $id;?></td>
<td><?php echo $productname;?></td>
<td><p id="display"><?php echo $status;?></p></td>
<td>
<select id="selectstatus">
<option>Pending</option>
<option>Delivered</option>
<option>Cancelled</option>
<option>Amount Paid</option>
</select>
</td>
</tr>
<?php
}
}
}
}
function getdata($statusid,$id){
$sql = $this->link->stmt_init();
if($sql->prepare("UPDATE ajaxselect SET status=? WHERE id=?")){
$sql->bind_param('si',$statusid,$id);
if($sql->execute()){
echo $statusid;
}
else
{
echo "Update Failed";
}
}
}
}
?>
【问题讨论】:
-
所有选择框的 ID 都相同?
-
不,它们是动态变化的,看代码在 processing.php 页面
<input type="hidden" id="getid" value="<?php echo $id;?>我刚刚隐藏了输入值。但可以获取它们以及如何获取它们 -
是的,但您始终检查的是同一个 ID。我发布了一个答案,所以你可以试试。
-
错误太多了,我不知道从哪里开始...首先...您不能拥有超过 1 个 ID,使用类。其次,你总是得到相同的字段......这就是为什么你总是更新第一条记录......我上面的那个人的想法是正确的,但他的答案也是错误的。您需要将 ID 添加到属性中,然后使用 $(this).attr(data-id) 或类似的东西获取它,或者将其全部存储在 js 对象中。
-
发布产品列表的 HTML 而不是图片。问题只是因为您使用了 ID,脚本一次又一次地更新同一行。请使用类,或使用 jQuery/javascript 对象提取值
标签: javascript php jquery mysql ajax