jQuery ajax() using success, error and complete vs .done(), .fail() and always()
JavascriptAjaxJqueryJavascript Problem Overview
The questions:
- Should we change our coding as suggested below?
- Is there a difference between
.done()
&success:
,.fail()
&error:
and.always()
&complete:
?
The preamble:
I was putting together a jQuery.ajax call, which I have done successfully in the past too. Something like this:
$.ajax(
{
url: someUrl,
type: 'POST',
data: someData,
datatype: 'json',
success: function (data) { someSuccessFunction(data); },
error: function (jqXHR, textStatus, errorThrown) { someErrorFunction(); }
});
While taking a quick look at some documentation, I came across a reference stating that The success, error and complete callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
We should therefore start coding something like this instead:
$.ajax( "example.php" )
.done(function (data) { someSuccessFunction(data); })
.fail(function (jqXHR, textStatus, errorThrown) { someErrorFunction(); })
.always(function() { alert("complete"); });
Javascript Solutions
Solution 1 - Javascript
Well there is no advantage of doing that in that particular situation.
The point of the .done()
.fail()
.always()
methods is that you can
- Attach multiple handlers
- Do so anywhere and not just when calling
$.ajax
If you are at the $.ajax
call site only attaching single handlers then those advantages don't really come into play.
So you can return the promise and others may attach their own handlers.
Example is refreshing plugins after ajax request:
$.ajaxPrefilter(function(opt, origOpt, jqxhr) {
jqxhr.always(function() {
$("[data-plugin]").plugin();
});
});