Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX error handling

Tags:

jquery

ajax

php

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

like image 502
Dave Kiss Avatar asked Jan 08 '10 22:01

Dave Kiss


People also ask

How do you handle errors in AJAX call?

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.

What is AJAX error function?

The ajaxError() method in jQuery is used to specify function to be run when an AJAX request fails. Syntax: $(document).ajaxError( function(event, xhr, options, exc) ) Parameter:: This method accepts single parameter function which is mandatory.

What is an ajaxError () in jQuery?

The ajaxError() method specifies a function to be run when an AJAX request fails. Note: As of jQuery version 1.8, this method should only be attached to document.


1 Answers

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);
   }
});
like image 65
Bill Avatar answered Oct 19 '22 22:10

Bill