Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to jquery ajax - .fail vs. :error

Which one should I use?

Is there any reason to use one rather than the other?

Is one better for error handling?

$.ajax({     url: url,     data: { start: start, end: end } }).done(function(data, textStatus, jqXHR) {     $('#myElement').append(data); }).fail(function() {     // report error     }); 

OR

$.ajax({     url: url,     data: { start: start, end: end },     success: function(data, textStatus, jqXHR) {         $('#myElement').append(data);     },     error: function(jqXHR, textStatus, errorThrown) {         // report error     } }); 
like image 222
PeteGO Avatar asked Oct 31 '12 22:10

PeteGO


People also ask

Is AJAX successful deprecated?

ajax function is deprecated.

How do you handle AJAX failure?

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 failure?

ajax method lets you set a timeout in milli seconds. When a timeout happens, The fail callback is called, with errorThrown set to "timeout". The request is aborted, meaning that even if the response arrives later on, your done callback is not called by jQuery.


1 Answers

The two options are equivalent.

However, the promise-style interface (.fail() and .done()) allow you to separate the code creating the request from the code handling the response.

You can write a function that sends an AJAX request and returns the jqXHR object, and then call that function elsewhere and add a handler.

When combined with the .pipe() function, the promise-style interface can also help reduce nesting when making multiple AJAX calls:

$.ajax(...)     .pipe(function() {          return $.ajax(...);     })     .pipe(function() {          return $.ajax(...);     })     .pipe(function() {          return $.ajax(...);     }); 
like image 53
SLaks Avatar answered Oct 09 '22 11:10

SLaks