Reputation: 14863
I'm trying to synchronize my ajax request using promises: My current code is this simple:
var ajax = undefined;
$.ajax({
type: 'put',
url: url,
data: data,
cache: false,
successs: function () {
},
error: function () {
}
}).done(function () {
alert('done');
});
This works fine as long as the ajax call is successful (statuscode 200) but when a call fails (e.g trhow an invalid url), the done isn't called anymore. How can I execute done, even if the ajax request fails=
Stefan
Upvotes: 0
Views: 3863
Reputation: 1074335
A couple of options for you:
Call the same function on success or failure. Functions don't have to be anonymous and defined inline, you can define them separately with names and reference them accordingly.
In your snippet, you're using both the older success
(although with an extra s
at the end) and error
and the newer done
, which means you're defining two different callbacks for success (success
and done
). Just one is sufficient.
Here's an example using success
and error
, passing null
into the handler on error
:
var ajax = undefined;
$.ajax({
type: 'put',
url: url,
data: data,
cache: false,
success: handler,
error: function() {
handler(null);
}
});
function handler() {
alert("Done");
}
Or using done
and fail
:
var ajax = undefined;
$.ajax({
type: 'put',
url: url,
data: data,
cache: false
}).done(handler).fail(function() {
handler(null);
});
function handler() {
alert("Done");
}
Alternately (or in combination), there's the complete
callback (the one you specify in options) and the always
callback (in the done
and fail
style), which are called regardless of success or failure (after the success or failure callbacks are done):
complete
:
var ajax = undefined;
$.ajax({
type: 'put',
url: url,
data: data,
cache: false,
success: handler,
error: function() {
handler(null);
},
complete: function() {
alert("Always called (after success/error)");
}
});
function handler() {
alert("Done");
}
always
:
var ajax = undefined;
$.ajax({
type: 'put',
url: url,
data: data,
cache: false
}).done(handler).fail(function() {
handler(null);
}).always(function() {
alert("Always called (after done/fail)");
});
function handler() {
alert("Done");
}
Upvotes: 5
Reputation: 1666
There is no need for done
$.ajax({
type: 'post',
url: url,
data: data,
cache: false,
success: function () {
alert('success');
},
error: function () {
alert('error');
},
complete: function(){
alert('complete');
}
});
Upvotes: 0
Reputation: 57316
Instead of done
function, you can use complete
setting:
$.ajax({
type: 'put',
url: url,
data: data,
cache: false,
successs: function () {
},
error: function () {
}
complete: function(jqXHR, textStatus) {
alert("Done");
});
complete
function executes after success
or error
. Have a look at jQuery ajax documentation for more details.
If you do not care about actual success
and error
callbacks and only want to do something once the call completes, regardless of the result, then omit success
and error
settings completely.
Upvotes: 0