我有一个数据表,该数据表是通过SQL提取到DataTables中的。我想使用AJAX运行SQL查询,该查询基于$id = $row["id"];
删除了行。
Index.php:
$link = mysqli_connect("localhost", "bradlyspicer_root", "", "bradlyspicer_ResellerDB");
$id = $_POST['id'];
$deleterow = "DELETE FROM Offences WHERE id = ?";
if($stmt = mysqli_prepare($link, $deleterow)){ // $link being your connection
mysqli_stmt_bind_param($stmt, "s", $id);
mysqli_stmt_execute($stmt);
echo 'success';
echo $id;
} else {
echo 'fail!';
printf("Error: %s.\n", mysqli_stmt_error($stmt));
}
Functions.php:
$id = $_POST['id'];
$deleterow = "DELETE FROM Offences WHERE id = ?";
if($stmt = mysqli_prepare($link, $deleterow)){ // $link being your connection
mysqli_stmt_bind_param($stmt, "s", $id);
mysqli_stmt_execute($stmt);
echo 'success';
} else {
echo 'fail!';
printf("Error: %s.\n", mysqli_stmt_error($stmt));
}
Custom.js:
$( ".delbtn" ).click(function(){
var itemID = $(this).attr("itemID");
console.log(itemID)
$.ajax({
url:"functions.php", //the page containing php script
data: { id: itemID}, // itemID passed as id
type: "POST", //request type
success:function(result){
alert(result);
},
error: function() {
alert('Error occured');
}
});
});
我找不到从$ Index.php到$ Functions.php的按钮中的$ id传递给我的地方,
更新:由于更新了脚本并尝试进行调试,因此输出的错误没有得到太多响应:
fail!Error: .
答案 0 :(得分:2)
Index.php:
添加一个删除按钮标识符类delbtn
和一个数据属性,该属性携带该行的ID data-itemID
<?php
while($row = mysqli_fetch_array($dataTablesResult)){
$id = $row["id"];
echo '
<tr>
<td>
<button type="button" data-itemID="'.$id.'" class="delbtn btn btn-danger" >Remove</button>
</td>
</tr>
';
}
?>
Functions.php:
ajax发送的捕获$_POST['id']
$id = $_POST['id'];
$deleterow = "DELETE FROM Offences WHERE id = ?";
if($stmt = mysqli_prepare($link, $deleterow)){ // $link being your connection
mysqli_stmt_bind_param($stmt, "s", $id);
mysqli_stmt_execute($stmt);
}
Custom.js:
单击具有.delbtn
类的按钮时,运行jQuery函数。从数据属性中捕获行ID并将其存储为$(this).data("itemID")
。然后在ajax请求中使用data: { id: itemID}
发送数据
$(".delbtn").click(function(){
itemID = $(this).data("itemID");
$.ajax({
url:"functions.php", //the page containing php script
data: { id: itemID}, // itemID passed as id
type: "POST", //request type
success:function(result){
alert(result);
}
});
});
答案 1 :(得分:1)
我想如果您更改此行:
mysqli_stmt_bind_param($stmt, "s", $id);
这是一个:
mysqli_stmt_bind_param($stmt, "i", $id);
可能有效