Php jqueryajax调用赢得';更新数据库
我一直在学习如何使用jQuery和AJAX更新数据库,这样在提交内容时就不需要刷新页面,但我有点卡住了 此示例非常简单-单击“接受”按钮,在数据库中,“接受”列将更新为“1”,而不是“0”。jQuery函数似乎工作正常,但该值未更新。我尝试过从Php jqueryajax调用赢得';更新数据库,php,jquery,Php,Jquery,我一直在学习如何使用jQuery和AJAX更新数据库,这样在提交内容时就不需要刷新页面,但我有点卡住了 此示例非常简单-单击“接受”按钮,在数据库中,“接受”列将更新为“1”,而不是“0”。jQuery函数似乎工作正常,但该值未更新。我尝试过从data:'id='+id切换到JSONdata:{id:data}方法,以及只使用.val()而不是.serializeArray(),但似乎没有任何效果。有什么建议吗 form.php <form id='acceptGoal' method='
data:'id='+id
切换到JSONdata:{id:data}
方法,以及只使用.val()
而不是.serializeArray()
,但似乎没有任何效果。有什么建议吗
form.php
<form id='acceptGoal' method='post'>
<input type='hidden' name='id' value='$gid'>
<input type='button' id='submit'>Accept?</button>
</form>
/* $gid is the unique identifier of each individual item to be accepted */
require 'core/initialize.php';
$query=$db->prepare("UPDATE goals SET accepted=:a WHERE id=:i");
$query->bindParam(":a", $a=1);
$query->bindParam(":i", $_POST['id']);
if ($query->execute()) {
echo "Done";
}
else {
echo "Something went wrong.";
}
accept.php
<form id='acceptGoal' method='post'>
<input type='hidden' name='id' value='$gid'>
<input type='button' id='submit'>Accept?</button>
</form>
/* $gid is the unique identifier of each individual item to be accepted */
require 'core/initialize.php';
$query=$db->prepare("UPDATE goals SET accepted=:a WHERE id=:i");
$query->bindParam(":a", $a=1);
$query->bindParam(":i", $_POST['id']);
if ($query->execute()) {
echo "Done";
}
else {
echo "Something went wrong.";
}
首先,结尾有语法错误,这里有一个额外的逗号:
$.ajax({
type: "POST",
url: "accept.php",
datatype: "json",
data: { id: data }, //<-------- Here is mistake
});
将其更改为:
<input type='hidden' id='id' name='id' value='$gid'>
您应该添加success和errorcallback,以检查ajax调用是否成功或是否发生错误:
$.ajax({
type: "POST",
url: "accept.php",
datatype: "json",
data: { id: data },
success:function(response){
alert(response);
},
error:function(response){
alert("error");
}
});
请看电视。表单是否正在提交,它发送了什么数据?服务器的响应是什么?如果将
print\r($\u POST)
添加到PHP脚本中,它会说什么?表单正在提交,但数据长度显然是0。我从print\r中看不到任何东西。这是我上传问题时的一个打字错误,代码中实际上不存在逗号。检查更新,您还访问了一个id不存在的隐藏字段,该字段使数据通过,但是数据库仍然不会更新?这是服务器端的问题,现在你已经检查了你的php代码
$.ajax({
type: "POST",
url: "accept.php",
datatype: "json",
data: { id: data }
});
$.ajax({
type: "POST",
url: "accept.php",
datatype: "json",
data: { id: data },
success:function(response){
alert(response);
},
error:function(response){
alert("error");
}
});