javascript - PHP AJAX 删除记录 - 只删除 1 次
问题描述
我正在使用 ajax 和 php 删除记录。当我单击按钮时,它会删除记录,但是当我单击删除另一条记录时,它什么也不做。我究竟做错了什么?
HTML
<form id="prop_remove">
<input type="hidden" name="id" id="last_id" value="<?php echo $id; ?>">
<input type="hidden" name="user" id="last_user" value="<?php echo $user; ?>">
<input type="button" name="submit" id="last_prop" class="button fullwidth margin-top-5" value="Delete">
</form>
AJAX
<script>
$(document).ready(function() {
$('#last_prop').click(function() {
var id = $('#last_id').val();
var user = $('#last_user').val();
$.ajax({
url: "delete.php",
method: "POST",
data: {
ilan_id: id,
ilan_user: user
},
success: function(response) {
if (response == 1) {
$('#last_prop').closest('tr').css('background', 'tomato');
$('#last_prop').closest('tr').fadeOut(800, function() {
$(this).remove();
});
} else {
alert('Invalid id');
}
}
});
});
});
</script>
PHP
<?php
require_once 'config.php';
$id = $_POST['ilan_id'];
$user = $_POST['ilan_user'];
$checkRecord = "SELECT * FROM last_tbl WHERE id = '$id' AND user = '$user'";
$check_result = mysqli_query($conn, $checkRecord);
$totalrows = mysqli_num_rows($check_result);
if($totalrows > 0){
$delete_sql = "DELETE FROM last_tbl WHERE id = '$id' AND user = '$user';";
$delete_result = mysqli_query($conn, $delete_sql);
echo 1;
exit;
}
?>
解决方案
您的问题是您正在覆盖 HTML 元素 ID。您可以删除表单并改用单个按钮,并通过data
按钮的属性传递数据。
用一个按钮替换您的表单
<button class="button fullwidth margin-top-5 last_prop" data-last-id="<?= $id; ?>" data-last-user="<?= $user; ?>">Delete</button>
然后调整您的 jQuery 以使用类last_prop
而不是 ID,并从data
我们上面设置的属性中获取值。
<script>
$(document).ready(function () {
$('.last_prop').click(function () {
var id = $(this).data('last-id');
var user = $(this).data('last-user');
$.ajax({
url:"delete.php",
method: "POST",
data: {ilan_id: id, ilan_user: user},
success:function(response){
if (response == 1 ){
$('#last_prop').closest('tr').css('background','tomato');
$('#last_prop').closest('tr').fadeOut(800,function(){
$(this).remove();
});
} else {
alert('Invalid id');
}
}
});
});
});
</script>
此外,您的查询可以减少到一个(您不需要SELECT
),并且应该使用准备好的语句。
<?php
require_once 'config.php';
$id = $_POST['ilan_id'];
$user = $_POST['ilan_user'];
$sql = "DELETE FROM last_tbl WHERE id = ? AND user = ?;";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $id, $user);
$stmt->execute();
if ($stmt->affected_rows) {
// rows were deleted
echo 1;
}
$stmt->close();
推荐阅读
- c - 如何从 char* 的地址获取字符串?
- css - ejs-lineargauge Majorticks 和 Minorticks Middle
- github - 拉网页(ghcr.io/***/:未授权 - Docker 和 Github 操作
- mqtt - 从一处管理多个 mqtt 设备
- azure - 我们可以限制 Azure 数据工厂 (ADF) 中 Git repo 链接/取消链接的操作吗?
- sql - Sql 查询以获取重叠日期间隔的外部
- split - Gnuplot 4.6 中的图例修改
- c# - Azure 函数使用来自事件中心的消息并将其发布到 REST API
- apache-pulsar - 在 kubernetes 集群上安装 Pulsar-manager
- react-native - 将 RTK-Query useLazyQuery 与 ReactNative 一起使用时,Jest 无法正确退出