我想删除数据库中的行而不重新加载页面。我写了以下代码。它会删除页面中的行但不会删除数据库中的行。这意味着连接不会进入ajax。请帮助。
<?php
$advances_result= mysqli_query($conn, "SELECT * FROM advances") or die("error");
?>
<table border>
<caption>ADVANCES</caption>
<tr>
<th>Date</th>
<th>EmpName</th>
<th>EmpCode</th>
<th>Amount</th>
<th>Comment</th>
<th>Action</th>
</tr>
<?php
while($row = mysqli_fetch_array($advances_result)){
?>
<tr>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['empname'];?></td>
<td><?php echo $row['empcode'];?></td>
<td style='text-align:right'><?php echo $row['amount'];?></td>
<td><?php echo $row['comment'];?></td>
<td><button class="delete" id="<?php echo $row['id']; ?>" > Delete</button></td>
</tr>
<?php
}
?>
</table>
'jquery part'
<script>
$(document).ready(function(){
$(".delete").click(function() {
if (confirm("Do you want to delete this row?"))
{
var row = $(this).parents('tr');
var id = row.attr("id");
var data = 'id=' + id ;
$.post({
type: "post",
url: "deleteadvances.php",
data: data,
cache: false,
success: function(){
row.slideUp('slow', function() {$(row).remove();});
}
});
}
return false;
});
});
</script>
'deleteadvances.php'页面:
<?php
include("connection.php");
$id = $_POST['id'];
mysqli_query($conn,"INSERT INTO advancehistory SELECT * FROM advances WHERE ID='".$id."'");
mysqli_query($conn,"DELETE FROM advances WHERE ID='".$id."'");
?>
答案 0 :(得分:0)
你需要在deleteadvances.php中测试mysqli_query的输出,如果一切正常,它会显示JSON Ok消息,可以在jQuery端使用$ .post轻松解析。
例如:{"deleted":"id"}
成功或{"error":404}
未找到错误。
答案 1 :(得分:0)
我认为您从javascript传递到ajax的ID不正确。
var data = 'id=' + id;
用字符串追加id&#39; id =&#39;现在它终于变成了一个字符串。当它传递给ajax时,只有一个值,而不是[key,value]对。所以,当你在php中访问它时,你会得到错误的id或Null值。
尝试:
$.post({
type: "post",
url: "deleteadvances.php",
datatype : 'json',
data: {
id : id
},
cache: false,
contentType : 'application/x-www-form-urlencoded; charset=utf-8'
});
答案 2 :(得分:0)
更改' deleteadvances.php '页面:
<?php
include ('connection.php');
$id=$_POST['id'];
$delete = "DELETE FROM table_name WHERE id=$id";
$result = mysqli_query($db,$delete) or die("Bad SQL: $delete");
?>