我想从数据库中删除一条记录,并且我想要使用ajax ..
所以我有一张桌子,我把它放在最后td
这个:
<input type='image' src='./img/delete.png' onClick='deleteUser(".$utentiIscritti[$i][0].");' />
这是我的deleteUser
功能:
function deleteUser(id){
$.ajax({
type:"post",
url: "deleteUserAjax.php",
data: {'id':id},
success: function(data){
console.log("OK");
location.reload();
},
error: function(xhr, status, error){
alert(xhr+"\n\n"+status+"\n\n"+error);
console.log("KO");
}
});
}
这是我的php页面连接到db并删除记录:
<?php
$USERDB = "u";
$PASSWORDDB = "p";
$NAMEDB = "d";
$queryDeleteUser = 'delete from user where id = "'.$_POST['id'].'"';
$conn = mysql_connect("localhost", $USERDB, $PASSWORDDB)
or die("Errore nella connessione al database: " . mysql_error());
mysql_select_db($NAMEDB) or die("Errore nella selezione del database: " . mysql_error());
mysql_query($queryDeleteUser) or die("Errore nella query: " . $queryDeleteUser . "\n" . mysql_error());
dbDisconnect($conn);
但我总是(从每个ajax请求)获得错误:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
iscritti.php:80
为什么???
答案 0 :(得分:1)
您可以考虑两种解决方案。
url: "deleteUserAjax.php"
,尝试使用绝对路径并检查结果(url: "http://yourdomain.com/deleteUserAjax.php"
)答案 1 :(得分:1)
也许让它更清洁:
HTML部分:
<input type='image' src='./img/delete.png' value='<?=$id?>'>
jQuery部分:
$(document).ready(function(){
$("#delete").on("click", function(){
var data = $(this).val();
$.ajax({
method: "POST",
url: "page_you_handle_it.php?action=delete",
data: {'id':id}
}).done(function(data){
//here you get response of your delete function!
});
});
});
PHP部分:
$host = "[HOST]"; //Like localhost
$user = "[USER]"; //Like root
$pass = "[PASS]"; //Like 123
$db = "[DB]"; //Like users
$con = mysqli_connect($host, $user, $pass, $db) or die ("Conntecting the Database gone wrong");
$id = $_POST['id'];
$query_str = "DELETE FROM user WHERE id = '$id'";
$query = mysqli_query($con, $query_str);
if (!$query) //Do not run the `$query` in the return parts because it already runs when you say `if (!$query)`
{
echo 'Delete gone wrong';
}
else
{
echo 'Delete succes!';
}