6

I've searched the questions on here, but I don't have a good understanding of how to use the error handling in jQuery's AJAX (im a noob, so it just really doesn't make sense.)

Can anybody describe this to a beginner? I'm currently posting information to a PHP script via AJAX, but want to allow jQuery to recognize if the returned data from the script is an error or success.

Thanks! Dave

4 Answers 4

20

The error return from the ajax call is returning the results from a page load that was not successful. It may be that your php page returns a valid page, but with results that are not what you want. This is handled withing the success return. Hopefully the following code snippit will help illustrate...

$.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
  • 1
    Bill, this looks helpful, can you give me an idea of what exactly the PHP script would be echoing that would allow for the jquery to pick up (i mean, i see that it'd be "Invalid Login", but can I also echo more information than that?)
    – Dave Kiss
    Commented Jan 8, 2010 at 22:45
  • +1 Great answer Bill! I do think the xhr parameter name in the success callback is misleading as it is only the data returned not the xhr object itself. Commented Jan 8, 2010 at 22:45
  • Dave, you can return whatever you want to return, just be aware of the dataType that you are using. For simple stuff like this example the default dataType is fine, for more complex data look at the other data types available. For example to use JSON data, have the php code send JSON data. Look at the jquery docs for $ajax to see how to set dataType, also look at the php docs for JSON methods. Doug, good point.
    – Bill
    Commented Jan 8, 2010 at 23:00
2

The jQuery AJAX error handling is implemented to handle if the HTTP Request has an error not if your script is returning "error" or "success". If the server throws an error (404 Not Found or 500 Server Error as an example) then it will trigger the error functions of jQuery. It can be handled a few ways, but one nice way is to show a div letting the user know there was an error.

HTML

<div id="error" style="display: none">There was an error processing your last request</div>

jQuery

$(function(){
   $("#error").ajaxError(function(){
      var $error = $(this);
      $error.slideDown(500, function(){
          window.setTimeout(function(){
              $error.slideUp(500);
          }, 2000);
      }); 
   });
});

If an error occurs, none of your "success" methods will fire, and that div will slide down, wait 2 seconds, then slide back up.

Testing your script for errors

As I mentioned what you described sounds like your server script is sending "error" or "success" or something similar back to the client.

If you are using a $.post, for example, your error handling code might look like this:

$.post('/your/url', { save_me: true }, function( data ){
   if(data == "error"){ 
      // handle error
   } else {
      // handle success
   }
}
2

This is only 1 approach. I am building an application that returns all of its data in JSON. If there is an error then the JSON message is changed to reflect this. Every return object has a "status" of either "success" or "error". If it is an error then there is an "error_message" part of the JSON that describes the error.

I hope that helps.

2

Even though it's not your problem, I'll post here since it's related.

With the recent JQuery v1.4 release, JSON responses are now validated. It broke my app because I returned:

 {success:true}

and now it's required to be

 {"success":true} // HAS to be double quotes, single won't do it

If incorrect, it calls the error handler. Easy fix but took a bit to figure out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.