为了账号安全,请及时绑定邮箱和手机立即绑定

AJAX总是认为php返回成功,即使失败

AJAX总是认为php返回成功,即使失败

PHP
GCT1015 2022-10-28 09:37:21
我有一个添加新用户帐户的 php 脚本。addAccount() 的一部分检查用户名是否有效,如果无效,则返回不可用的异常(出现致命错误)。我的问题是 AJAX 将一切都解释为成功并无论如何都显示成功消息。如何解决此问题或至少捕获致命错误并显示正确的消息?$(document).on('click', '#createUserBtn', function(e){    e.preventDefault();    $.ajax({        url:'addUser.php',        type:'post',        data:$('#addUser').serialize(),        success:function(){                toastr.success("User successfully added!");            },        error: function(){            toastr.warning('Uh-oh! Something went wrong with adding this user!');        }    });});添加用户.php<?phpsession_start();/* Include the database connection file (remember to change the connection parameters) */require './db_inc.php';/* Include the Account class file */require './account_class.php';  $type = $_POST['type'];  $username = $_POST['uname'];  $password = $_POST['password'];  $comp = $_POST['company'];  $email = $_POST['email'];  $fname = $_POST['fname'];  $lname = $_POST['lname'];  $query = $pdo->query("SELECT * FROM accounts WHERE email ='".$email."'");$account = new Account();// Will print all the values received.    $newId = $account->addAccount($username, $password, $comp, $email, $fname, $lname, $type);    header('Location: ./dashboard.php?user='.$username);?>这是使用的 addAccount 函数...    public function addAccount(string $name, string $passwd, string $comp, string $email, string $fname, string $lname, string $type): int    {        /* Global $pdo object */        global $pdo;        /* Trim the strings to remove extra spaces */        $name = trim($name);        $passwd = trim($passwd);        /* Check if the user name is valid. If not, throw an exception */        if (!$this->isNameValid($name))        {            throw new Exception('Invalid user name');        }        /* Check if the password is valid. If not, throw an exception */        if (!$this->isPasswdValid($passwd))        {            throw new Exception('Invalid password');        }
查看完整描述

2 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

首先,如果您从 javascript 请求某些内容,则无法通过 php 重定向用户,请从 addUser.php 中删除此行


header('Location: ./dashboard.php?user='.$username);

现在要将结果从 php 返回到客户端,您必须DIE使用带有值的 php,最好的方法是 JSON


在 addUser.php 检查你想要什么并返回如下值:


    <?php


session_start();

/* Include the database connection file (remember to change the connection parameters) */

require './db_inc.php';


/* Include the Account class file */

require './account_class.php';


  $type = $_POST['type'];

  $username = $_POST['uname'];

  $password = $_POST['password'];

  $comp = $_POST['company'];

  $email = $_POST['email'];

  $fname = $_POST['fname'];

  $lname = $_POST['lname'];

  $query = $pdo->query("SELECT * FROM accounts WHERE email ='".$email."'");


$account = new Account();

// Will print all the values received.

    $newId = $account->addAccount($username, $password, $comp, $email, $fname, $lname, $type);

        if(intval($newId) > 0) // if user created

            die(json_encode(array('status' => 'ok')));

        else

            die(json_encode(array('status' => 'error')));

    ?>

然后更改您的客户端,如下所示:


$(document).on('click', '#createUserBtn', function(e){

    e.preventDefault();

    $.ajax({

        url:'addUser.php',

        type:'post',

        data:$('#addUser').serialize(),

        dataType: "json", // <- Add this line

        success:function(response){ // <- add response parameter

                //Here check result

                if(response['status'] == 'ok')

                    toastr.success("User successfully added!");

                else

                    toastr.warning('Uh-oh! Something went wrong with adding this user!');


            },

        error: function(){


        },

    statusCode: { // <- Add this property

        500: function() {

             toastr.warning('Uh-oh! Something went wrong with adding this user!');

        }

    }

    });

});


查看完整回答
反对 回复 2022-10-28
?
慕桂英546537

TA贡献1848条经验 获得超10个赞

您可以使用http_response_code()返回 HTTP 错误代码(通常代码 500 :内部服务器错误)。

您可以使用 try/catch 块来做到这一点:

try

{

     ...

     $account = new Account();

     // Will print all the values received.

     $newId = $account->addAccount($username, $password, $comp, $email, $fname, $lname, $type);

     header('Location: ./dashboard.php?user='.$username);

}

catch(Exception $e)

{

    http_response_code(500);

    exit();

}


查看完整回答
反对 回复 2022-10-28
  • 2 回答
  • 0 关注
  • 79 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信