繁体   English   中英

如何使用ajax更新数据库中的记录并单击按钮时删除表行?

[英]How update records in the database and remove a table row on button click using ajax?

因此,我创建了带有动态行的HTML表。 每行最后都有一个按钮。 单击特定行上的该按钮时,需要删除该行而不刷新页面。

所以我试图通过单击按钮时更改数据库中列的值来实现。 我的数据库中有一个名为“状态”的字段,该字段最初设置为“未选中”。 但是,当我单击按钮时,将触发更新查询,因此将特定行上的“状态”字段更改为“选中”,并删除该特定行。

newCust.php

<table class="table table-bordered table-striped table-light table- 
responsive text-nowrap">
<thead class="thead-dark">
<tr>
<th class="col"><label> nID</label></th>
<th class="col"><label> CUSTOMER NAME </label></th>
<th class="col"><label> ADDRESS </label></th>
<th class="col"><label> CITY </label></th>
<th class="col"><label> STATUS </label></th>
</tr>
</thead>
<tbody>

<?php
<!-- GETTING DATA FROM THE TABLE WHERE STATUS FIELD IS UNCHECKED -->
$query = "select * from mx_newcustomer where status = 'unchecked'";
$result = mysqli_query($db,$query);
while($res = mysqli_fetch_array($result)){
$nID = $res['nID'];
?>
<tr>
<td><?php echo $nID;  ?></td>
<td><?php echo $res['customername'];  ?></td>
<td><?php echo $res['address'];  ?></td>
<td><?php echo $res['city'];  ?></td>
<td><button type="button" id="button<?php echo $nID;  ?>" class="btn btn- 
dark" >Ok</button></td>
</tr>

<script>
<!-- AJAX TO UPDATE RECORDS IN THE DATABASE-->
$(document).ready(function () {
$("#button<?php echo $nID ?>").click(function(){
alert('Test');
jQuery.ajax({
type: "POST",
url: "updateCust.php",

<--TRYING TO 
PASS THE CLICKED BUTTON ID. I BELIEVE THIS IS WHAT I'M DOING WRONG-->
data:  {"nID":$('#button<?php echo $nID ?>').serialize()}, 
success: function(response)
{
 alert("Record successfully updated");
}
});
});
});

</script>

updateCust.php

$db = mysqli_connect("credentials");
$nID = $_POST['nID'];
$query = "UPDATE mx_newcustomer SET status = 'checked' WHERE nID = 
'$nID'";
$res = mysqli_query($db, $query);

error_reporting(E_ALL);
ini_set('display_errors','On');

我没有收到任何错误,但是更新查询也没有被触发。 预期的结果是删除未单击页面的单击按钮的表行。

不要使用.serialize() ,它以name=value的形式返回一个字符串。 但是您的按钮没有名称或值,因此没有要序列化的内容。

更改为:

data:  {"nID": <?php echo $nID ?>}, 

要删除该行,可以使用:

success: function() {
    $("#button<?php echo $nID?>").closest("tr").remove();
}

暂无
暂无

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

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