【问题标题】:Ajax PHP - Check returned response/data value from phpAjax PHP - 检查从 php 返回的响应/数据值
【发布时间】:2023-04-11 06:26:01
【问题描述】:

基本上,我正在验证注册表单并使用 ajax 调用 php 脚本来检查电子邮件地址是否已存在或查询是否执行。如果一个电子邮件地址已经存在(通过计数查询检查),我将向 ajax 函数回显一个错误(通过响应) - 但是它没有被读取。

我尝试研究类似的主题,但没有成功。

ajax

$.ajax({
                type: 'POST',
                url: 'signup-user.php',
                dataType: 'text',
                data: $('form').serialize(),
                success: function(response) {

                        if(response == "error-email-exists"){
                            $('#errorMsg').html("An account is already assosciated with the email adress you entered.");
                            $('#errorMsg').hide().stop(true,true).fadeIn(600);
                        }else if(response == "success"){
                            window.location = "index.php";
                        }else{
                            $('#errorMsg').html(response);
                            $('#errorMsg').hide().stop(true,true).fadeIn(600);
                        }


                }
            });

php


<?php
    session_start(); 
    include("conn.php");

    $post_firstName = $_POST['firstName'];
    $post_lastName = $_POST['lastName'];
    $post_dateofBirth = $_POST['dateofBirth'];
    $post_gender = $_POST['gender'];
    $post_propertyNo = $_POST['propertyNo'];
    $post_propertyAddress = $_POST['propertyAddress'];
    $post_streetAddress = $_POST['streetAddress'];
    $post_locality = $_POST['locality'];
    $post_email = $_POST['email'];
    $post_password = $_POST['password'];


    $checkexistsQuery = $conn->prepare('SELECT count(*) AS countExists FROM tbl_account acc WHERE acc.email = ?');

    $checkexistsQuery->bind_param('s', $post_email); 
    $checkexistsQuery->execute();

    $checkexistsQuery->store_result();
    $checkexistsQuery->bind_result($countExists);
    $checkexistsQuery->fetch();

    if($countExists > 0){
        echo 'error-email-exists';
    }else{
        $signupQuery = $conn->prepare('insert into tbl_account (name, surname, email, password, dob, genderID, propertyNumber, propertyAddress, streetAddress, localityID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');

        $signupQuery->bind_param('ssssssssss', $post_firstName,$post_lastName,$post_dateofBirth,$post_gender,$post_propertyNo,$post_propertyAddress,$post_streetAddress,$post_locality,$post_email,$post_password); 

        if($signupQuery->execute()){
            echo 'success';
        }else{
            echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
        }


    }

?>









问题是没有读取“错误电子邮件存在”和“成功”消息。

【问题讨论】:

  • “不被阅读”是什么意思?具体发生了什么?
  • 如果&lt;?php之前确实有一个新行,那么一些数据会在任何东西之前发送(并且响应将不同于'error-email-exists'
  • console.log(response) 的结果是什么?
  • success 块旁边写一个error: function(error) { console.log(error)} 块以确保输入success
  • 检查是否没有返回空格,因为这会破坏您的response == "error-email-exists" 检查。正是由于这个原因,返回序列化响应格式是更好的做法。快速解决方法是 response.trim() === 'error-email-exists',但我建议使用 JSON 来完全避免该问题。

标签: javascript php jquery ajax


【解决方案1】:

重构您的代码如下。使用 json 类型作为 contentType 并将 error 方法添加到您的 ajax。使用 json,您将更加灵活,并有机会添加结构化数据,例如错误、消息甚至标记。

js:

$.ajax({
    type: 'POST',
    url: 'signup-user.php',
    dataType: 'json',
    data: $('form').serialize(),
    success: function (response) {
        if (response.error) {
            $('#errorMsg').html(response.message);
            $('#errorMsg').hide().stop(true, true).fadeIn(600);
        } else {
            if (response.exists) {
                $('#errorMsg').html("An account is already assosciated with the email adress you entered.");
                $('#errorMsg').hide().stop(true, true).fadeIn(600);
            } else {
                window.location = "index.php";
            }
        }
    },
    error: function (error) {
        console.log(error);
    }
});

php:

<?php
    session_start(); 
    include("conn.php");

    $post_firstName = $_POST['firstName'];
    $post_lastName = $_POST['lastName'];
    $post_dateofBirth = $_POST['dateofBirth'];
    $post_gender = $_POST['gender'];
    $post_propertyNo = $_POST['propertyNo'];
    $post_propertyAddress = $_POST['propertyAddress'];
    $post_streetAddress = $_POST['streetAddress'];
    $post_locality = $_POST['locality'];
    $post_email = $_POST['email'];
    $post_password = $_POST['password'];


    $checkexistsQuery = $conn->prepare('SELECT count(*) AS countExists FROM tbl_account acc WHERE acc.email = ?');

    $checkexistsQuery->bind_param('s', $post_email); 
    $checkexistsQuery->execute();

    $checkexistsQuery->store_result();
    $checkexistsQuery->bind_result($countExists);
    $checkexistsQuery->fetch();

    $response = [];
    $response['error'] = false;

    if($countExists > 0){
        $response['exists'] = true;
    }else{
        $signupQuery = $conn->prepare('insert into tbl_account (name, surname, email, password, dob, genderID, propertyNumber, propertyAddress, streetAddress, localityID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');

        $signupQuery->bind_param('ssssssssss', $post_firstName,$post_lastName,$post_dateofBirth,$post_gender,$post_propertyNo,$post_propertyAddress,$post_streetAddress,$post_locality,$post_email,$post_password); 

        if($signupQuery->execute()){
            $response['exists'] = false;
        }else{
            $response['error'] = true;
            $response['message'] = "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
        }
    }

    echo json_encode($response);
?>

【讨论】:

  • 编辑:这不起作用,并在控制台上返回:prntscr.com/p7p0ub
  • 对不起。缺少一个错字$ -> echo json_encode($response);。我更新了答案。
  • 谢谢!一个快速的问题 - response['error'] 是否模棱两可,因为如果错误由 error: function(error)?? 处理
  • 没有。这个名字由你决定。 function(error) 在响应状态不是 200 时触发(服务器错误,例如状态 500)。
猜你喜欢
  • 2014-01-01
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多