Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if AJAX request was successful in jQuery

I've been checking to make sure my AJAX requests are successful by doing something like this:

$.post("page.php", {data: stuff}, function(data, status) {
    if(status == "success") {
        //Code here
    }
    else {
        //Error handling stuff
    }
});

Is checking the status variable the best way to go about doing this, or is there a better way to make sure the request actually went through? I'm considering a "successful" request to be a request that hits the page I'm posting to successfully without timing out (if the server was down and an AJAX request was made right before it went down as an example) or returning any kind of 404 or 500 error.

like image 681
Aaron Avatar asked Nov 15 '11 14:11

Aaron


2 Answers

By calling $.post that way, you automatically pass only in a success handler function.

If something on the request went wrong, this method is not even executed.

To have more control either use $.ajax() directly, or pass in fail handlers. That could look like

$.post("page.php", {data: stuff}, function(data, status) {
   // we're fine here
}).fail(function(err, status) {
   // something went wrong, check err and status
});

The same thing using .ajax():

$.ajax({
   type: 'POST',
   url: 'page.php',
   data: stuff,
   success: function( data ) {
   },
   error: function(xhr, status, error) {
      // check status && error
   },
   dataType: 'text'
});

You can even pass more ajax event handler to $.ajax, like beforeSend to modify/read XHR headers or complete to have a handler which fires either way (error or not) when the requests finished.

like image 56
jAndy Avatar answered Oct 19 '22 09:10

jAndy


I prefer to use the ajax call, as it has an explicit success handler

$.ajax({
url: "page.php",
data: stuff,
success: function(response){
console.log("success");
}
});

I'd also recommend using firebug or webkit similar, then you can track the requests and check the parameters!

like image 33
Andrew Dover Avatar answered Oct 19 '22 09:10

Andrew Dover