AJAX:我能正确插入数据吗?
问题描述:
我在这里阅读了许多类似的线索,看看我做错了什么,但我的AJAX调用似乎是正确的。我在这里错过了什么?没有警报弹出,所以我认为这是JS方面。AJAX:我能正确插入数据吗?
$("#SignupSubmit").click(function()
{
var fName = $("#txtSignFName").val();
var lName = $("#txtSignLName").val();
var email = $("#txtSignEmail").val();
var pw = $("#txtPW").val();
if(fName == "" || lName == "" || email == "" || pw == "")
{
alert();
}
else
{
$.ajax({
type: "POST",
url: "actionPages/signUp.php",
dataType: 'json',
data: {
fName:fName,
lName:lName,
email:email,
pw:pw
},
success: function(response) {
alert(response);
}
});
}
});
而PHP(这是正确的?):
<?php
require "../connectionPages/localConnect.php";
$fName = $_POST["fName"];
$lName = $_POST["lName"];
$email = $_POST["email"];
$pw = $_POST["pw"];
if($fName == null || $lName == null || $email == null || $pw == null)
$message = "missing required data";
else
{
$SQL = "INSERT INTO `customer/User` (custFName,
custLName,
custEmail,
custPassword)
VALUES ('$fName', '$lName','$email', '$pw')";
$mysqli->query($SQL);
if($mysqli->affected_rows > 0)
{
$message = "Record successfully inserted <br><a href='..'>Back to Main Page</a>";
$SQL = $mysqli->insert_id; /* $SQL = "SELECT max(custID) as ID FROM `customer/User`"; */
$res = $mysqli->query($SQL) or trigger_error($mysqli->error."[$SQL]");
json_encode($res);
}
else {
$message = "Unable to insert record: " . $mysqli->error;
}
$mysqli->close();
}
答
第一阶段更新数据部分下面的代码。
data: {
"fName":fName,
"lName":lName,
"email":email,
"pw":pw
},
而你正在试图获得最后插入的ID。是吗?如果是使用
$mysqli->insert_id;
,而不是选择查询
答
在AJAX
$.ajax({
type: "POST",
url: "actionPages/signUp.php",
dataType: 'json',
data: {
"fName":fName,
"lName":lName,
"email":email,
"pw":pw
},
success: function(response) {
var res=eval(response);
alert(res.id);
}
});
而在你的PHP页面执行此操作。这样做:
if($mysqli->affected_rows > 0)
{
$message = "Record successfully inserted <br><a href='..'>Back to Main Page</a>";
$lastid = $mysqli->insert_id; /* $SQL = "SELECT max(custID) as ID FROM `customer/User`"; */
// $res = $mysqli->query($SQL) or trigger_error($mysqli->error."[$SQL]");
echo json_encode(array('id'=>$lastid));
}
我希望它能帮助
哦。它仍然不起作用。我没有注意到。是的,我试图得到最后的ID – Calisto
检查您的浏览器控制台,并在发送数据或发送数据之后发现问题。在这里发布控制台消息以进一步帮助... – Naga
add'error:function(e){console.log(e); '''成功后':function(response){alert(response); }' – Naga