即使失败,AJAX始终认为php返回成功

时间:2020-03-10 20:54:40

标签: javascript php ajax

我有一个添加新用户帐户的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!');
        }
    });
});

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

        /* Check if an account having the same name already exists. If it does, throw an exception */
        if (!is_null($this->getIdFromName($name)))
        {
            throw new Exception('User name not available');
        }

        /* Finally, add the new account */

        /* Insert query template */
        $query = 'INSERT INTO login.accounts (account_name, account_passwd, fname, lname, company, email, user_type) VALUES (:name, :passwd, :fname, :lname, :comp, :email, :type)';

        /* Password hash */
        $hash = password_hash($passwd, PASSWORD_DEFAULT);

        /* Values array for PDO */
        $values = array(':name' => $name, ':passwd' => $hash, ':lname' => $lname, ':fname' => $fname, ':comp' => $comp, ':email' => $email, ':type' => $type);

        /* Execute the query */

            $res = $pdo->prepare($query);
            $res->execute($values);

        /* Insert query template */





        /* Return the new ID */
        return $pdo->lastInsertId();
    }

2 个答案:

答案 0 :(得分:0)

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

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

    function doSomething() {
        var url = px_alls['txtUrl'].value;
        var clientId = px_alls['txtClientID'].value;

    }

答案 1 :(得分:0)

首先,如果您从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')));
    ?>

然后按如下所示更改您的clientSide:

$(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!');
        }
    }
    });
});