"> AJAX $-6ren">
gpt4 book ai didi

javascript - PHP AJAX 删除记录 - 删除仅有效 1 次

转载 作者:行者123 更新时间:2023-11-29 15:58:49 25 4
gpt4 key购买 nike

我正在使用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();

关于javascript - PHP AJAX 删除记录 - 删除仅有效 1 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56322798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com