AJAX:我正确地插入数据吗?

时间:2016-12-14 02:42:18

标签: php mysql ajax

我在这里阅读了许多类似的线程,看看我做错了什么,但我的AJAX调用似乎是正确的。我在这里错过了什么?没有警报弹出,所以我认为它是JS方面。

$("#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();

}

2 个答案:

答案 0 :(得分:1)

第一阶段更新数据部分中的以下代码。

data: {
            "fName":fName,
            "lName":lName,
            "email":email,
            "pw":pw
        },

并且您正在尝试获取最后插入的ID。是吗?如果是这样的话

$mysqli->insert_id;

而不是选择查询

答案 1 :(得分:0)

在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));
}

我希望它有所帮助