The questions:
.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"); });
success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.
ajax post method. The reason was my response was not in the JSON format so there was no need for the dataType: 'json' line in the submit method. In my case, the returned response was in text format that's why it was not going to success event. Solution: Remove dataType: 'json' line.
What is AJAX success? AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.
Well there is no advantage of doing that in that particular situation.
The point of the .done()
.fail()
.always()
methods is that you can
$.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(); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With