How to receive error in jQuery AJAX response?

2020-07-27 18:52发布

I am using jQuery $.ajax() function to perform a database insert operation on a php page. So, on success it will do the regular operation but I want the ajax call to receive error if the update operation fails.

So it should be:

  1. $.ajax -> call php function
  2. Receive success on successful record insert
  3. Receive error on unsuccessfull insert

So, should I do a return false; from my php function? I think the $.ajax() success or error depends if the AJAX call was successful or not. So, I think even if I return false; from my php function it will still be considered a "success" for the ajax call. Right

标签: php jquery ajax
6条回答
叼着烟拽天下
2楼-- · 2020-07-27 19:35

Ajax is happening on the client.

Your PHP is over on the server.

Here's an excellent example that might help:

jQuery AJAX error handling


    $.ajax({
        type: "POST",
        url: "login.php",
        data: "action=login&user=" + user + "&pass=" + pass,
        success: function(xhr){
            if ((xhr == "Invalid Login") 
                    || (xhr == "Invalid charaters in username.") 
                    || (xhr == "Missing username or password.")
                    || (xhr == "Unknown Error")) {
                $("#loginMessageContent").html(xhr);
            }
            else {
                simplemodalClose (dialog);
            }
       }, 
       error: function(xhr) {
           alert ("Oopsie: " + xhr.statusText);
       }
    });
查看更多
老娘就宠你
3楼-- · 2020-07-27 19:36

This is simple, in short: you can catch any thing returned from PHP.

IN DETAIL: the below code snippet may help you clearly understand the issue.

PHP

$result = //your database result
if($result){
    //Print any success message you want the user to see   
    echo "Success";
}else{
    //Print any error message you want the user to see   
    echo "Error";
}

JQUERY

$.ajax({
    type: "POST",
    url: "controller.php",
    data: params,
    success: function(msg){

    //Alert the returned message to the user,
    //the variable msg already contains your message 
    //whether it is success or error,
    //it can even contain HTML or JavaScript
        alert(msg);
    }
});
查看更多
爷、活的狠高调
4楼-- · 2020-07-27 19:46

You need to handle PHP's success/error inside your $.ajax() success: function

Assume this is your ajax.php:

if($whatever)
{
  echo 'success';
}
else
{
  echo 'fail';
}

Assume this is your javascript $.ajax():

success: function(data)
{
    switch(data)
    {
        case 'success':
            // handle good logic
            break;
        case 'fail':
        default:
            // handle bad logic
            break;
    }
}
查看更多
男人必须洒脱
5楼-- · 2020-07-27 19:48

You could return the error message in your server response (or using JSON) as someone suggested. But I don't like it too much because this pollutes the data returned.

I like another way I've been using recently, which involves creating a custom HTTP header to inform if there was an error.

PHP code:

if($there_was_error){
   header("DB_SUCCESS: 0"); //Sends a custom header
}else{
   header("DB_SUCCESS: 1");
}

jQuery code:

$.ajax({
  ...
  success: function(data, status, xhr){
     //You can use your 'data' var as always
     if(xhr.getResponseHeader("DB_SUCCESS") == 1){
        alert("Save successful");
        //Your regular sutff
     }else{
        alert("Save failed");
     }         
  }
  ...
})

As you can see, we created a custom HTTP header, called DB_SUCCESS to be used as metadata, so we can assign it server-side (php) and read it with client-side (javascript) to know if there was an error.

Hope this helps. Cheers

查看更多
淡お忘
6楼-- · 2020-07-27 19:48

I would build up an array in PHP. Such as

$status['completed'] = true;
$status['message'] = "Completed";

Depends on how you go with insert change those two values.

Then I would do http://php.net/manual/en/function.json-encode.php json_encode and echo it out. Your jQuery would receive JSON and if the completed is true then its all fine. If false, check the message.

You could also use getJSON method from jQuery to make it even easier.

http://api.jquery.com/jQuery.getJSON/

查看更多
Anthone
7楼-- · 2020-07-27 19:56

I evaluate response from the server and if error occurred in the PHP, it simply outputs JavaScript code to show error.

Works well with all sorts of things including re-login on session-timeouts, access restrictions, exception handling and everything else.

I wish this approach would be more popular.

https://github.com/atk4/atk4/blob/master/templates/js/atk4_univ.js#L413

查看更多
登录 后发表回答