简体   繁体   English

处理 Ajax 响应

[英]Handling Ajax Response

I'm creating a user registration form for my website and am using ajax to handle server side process.我正在为我的网站创建用户注册表并使用 ajax 来处理服务器端进程。 My problem is the handling of the response from my php code.我的问题是处理来自我的 php 代码的响应。 Upon execution of the server side, the possible responses from it can be success (registered user), database connect error, empty field(s) error or failure to execute sql query (input(s) already exist in a unique sql field eg username, email).在服务器端执行时,它可能的响应可以是成功(注册用户)、数据库连接错误、空字段错误或无法执行 sql 查询(输入已存在于唯一的 sql 字段中,例如用户名) , 电子邮件)。 I want to know how I'm able to get the correct response for each of these to display a message to the user.我想知道我如何能够获得每个这些的正确响应以向用户显示一条消息。 What I have:我拥有的:

JS JS

  $.ajax({
    type: "post",
    url: "userRegistration.php",
    data: {
      firstname: firstname,
      surname: surname,
      email: email,
      usernameSignup: username,
      passwordSignup: password,
      passwordConfirm: passwordConfirm
    },
    dataType: "json",
    success: function(data) {
      console.log(data.status);
      if (data.status == "success") {
        console.log("Registration was successful");
        //Do success stuff
      } else if (data.status == "error") {
        console.log("Didn't Execute Query");
        // Do error stuff
      } else if (data.status == "connectionError") {
        console.log("Failed to connect to database");
        // Do error stuff
      } else {
        console.log("Empty fields");
        // Do error stuff
    }
  });

PHP PHP

<?php
// try catch statement to connect to database through getConnection() function in dbConn.php file
try {
    // try to connect to database
    require_once("dbConn.php");
    $dbConn = getConnection();
} catch (Exception $e) {
    // database connect error
    //echo "A problem occured: " . $e->getMessage();
    $response_array["status"] = "connectionError";
}

// Form validation for POST method to check fields are not empty
if (!empty($_POST['firstname'])) {
    $firstname = filter_has_var(INPUT_POST, 'firstname') ? $_POST['firstname'] : null;
    $firstname = trim($firstname);
} else {
    echo "A first name must be entered.<br/>";
}

// Same validation for other fields

// If all the previous steps are valid and variables are set, try to run the SQL query to make new account.
if (!empty($firstname) && !empty($surname) && !empty($email) && !empty($usernameSignup) && !empty($passwordHash)) {
    try {
        $sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
        VALUES ('$firstname', '$surname', '$email', 0, '$usernameSignup', '$passwordHash')";
        $execute = $dbConn->exec($sqlQuery);
        $response_array["status"] = "success";
    } catch (PDOException $e) {
        // failure to execute error
        //echo $sqlQuery . "<br>" . $e->getMessage();
        $response_array["status"] = "error";
    }
} else {
    // empty field(s) error
    $response_array["status"] = "empty";
}

// send the response
header("Content-type: application/json");
echo json_encode($response_array);
exit;

The success status handler works correctly but I am unable to get the error status handler when I try to pass data into the database when it already exists or the empty status handler for empty fields.成功状态处理程序正常工作,但是当我尝试将数据传递到数据库时,当数据已经存在或空字段的空状态处理程序时,我无法获得错误状态处理程序。 I also don't know of a way to check for the connectionError status handler.我也不知道有什么方法可以检查 connectionError 状态处理程序。 Any advice/suggestions to handle these responses would be appreciated.任何处理这些响应的建议/建议将不胜感激。

When you detect an error, you need to skip all the rest of the code until sending the JSON response.当您检测到错误时,您需要跳过所有其余代码,直到发送 JSON 响应。 Eg if you get a connectionError , you shouldn't then try to perform the query;例如,如果您收到connectionError ,则不应尝试执行查询; that will get an error, and replace $response_array['status'] = 'connectionError' with $response_array["status"] = "error" , so you'll report the wrong type of error.这将得到一个错误,并将$response_array['status'] = 'connectionError'替换$response_array["status"] = "error" ,因此您将报告错误类型的错误。

Also, form validation errors need to be returned in the JSON response, not echoed directly.此外,表单验证错误需要在 JSON 响应中返回,而不是直接回显。

One way to accomplish this is to nest your try/catch statements.实现此目的的一种方法是嵌套您的try/catch语句。

<?php
// try catch statement to connect to database through getConnection() function in dbConn.php file
try {
    // try to connect to database
    require_once("dbConn.php");
    $dbConn = getConnection();

    // Form validation for POST method to check fields are not empty
    if (!empty($_POST['firstname'])) {
        $firstname = filter_has_var(INPUT_POST, 'firstname') ? $_POST['firstname'] : null;
        $firstname = trim($firstname);
    } else {
        $response_array["status"] = "validationError";
        $response_array["message"] = "A first name must be entered.";
    }

    // Same validation for other fields

    // If all the previous steps are valid and variables are set, try to run the SQL query to make new account.
    if (!empty($firstname) && !empty($surname) && !empty($email) && !empty($usernameSignup) && !empty($passwordHash)) {
        try {
            $sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
        VALUES ('$firstname', '$surname', '$email', 0, '$usernameSignup', '$passwordHash')";
            $execute = $dbConn->exec($sqlQuery);
            $response_array["status"] = "success";
        } catch (PDOException $e) {
            // failure to execute error
            //echo $sqlQuery . "<br>" . $e->getMessage();
            $response_array["status"] = "error";
        }
    } else {
        // empty field(s) error
        $response_array["status"] = "empty";
    }

} catch (Exception $e) {
    // database connect error
    //echo "A problem occured: " . $e->getMessage();
    $response_array["status"] = "connectionError";
}

// send the response
header("Content-type: application/json");
echo json_encode($response_array);
exit;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM