success is only triggered when an AJAX call is successful, i.e. ultimately returns HTTP status 200. error triggered if it fails, and complete when the request ends, regardless of success.
In jQuery 1.8, the jqXHR object (returned by $.ajax ) success was replaced by done , error by fail and complete by always .
However, you can still initialize the AJAX request with the old syntax. So they do similar things:
// set success action before making the request $.ajax({ url: '...', success: function(){ alert('AJAX successful'); } }); // set success action just after starting the request var jqxhr = $.ajax( "..." ) .done(function() { alert("success"); });
This change is compatible with jQuery 1.5 pending object . Deferred (and now Promise , which has full browser support in Chrome and FX), allows you to chain asynchronous actions:
$.ajax("parent"). done(function(p) { return $.ajax("child/" + p.id); }). done(someOtherDeferredFunction). done(function(c) { alert("success: " + c.name); });
This chain of functions is easier to maintain than the nested pyramid of callbacks you receive with success .
However, note that done now deprecated in favor of the Promise syntax, which then uses instead:
$.ajax("parent"). then(function(p) { return $.ajax("child/" + p.id); }). then(someOtherDeferredFunction). then(function(c) { alert("success: " + c.name); }). catch(function(err) { alert("error: " + err.message); });
This is worth accepting, because async and await extend promises enhanced syntax (and error handling):
try { var p = await $.ajax("parent"); var x = await $.ajax("child/" + p.id); var c = await someOtherDeferredFunction(x); alert("success: " + c.name); } catch(err) { alert("error: " + err.message); }
Keith Jan 13 2018-12-12T00: 00Z
source share