Reputation: 91
When I use success callback this solution works fine, but when I use .done() this fail, how I can retry send enqueued ajax request with original .done() .fail() and complete() registered callbacks?
var requestQueue = [];
$.ajaxSetup({
cache: false,
beforeSend: function (jqXHR, options) {
if(true){ //any condition 'true' just demonstrate
requestQueue.push({request:jqXHR,options:options});
//simulate process this queue later for resend the request
window.setTimeout(function(){
//this will work with success callbak option,
//but with .done() the console.log("Well Done!");
// will fail
$.ajax($.extend(requestQueue.pop().options, {global:false, beforeSend:null}));
}, 3000)
return false;
}
}
});
$.ajax({
url:"TesteChanged.html",
error: function(){
console.log("Oh nooooo!");
}
}).done(function(){
console.log("Well Done!");
});
I wanna enqueue a ajax call (based in a condition) to resend later, but when a resend it, .done()/.fail() original callback must be called. With 'success' callback option this code works fine.
Upvotes: 1
Views: 1296
Reputation: 7823
I use this for delaying AJAX requests:
Global variant:
var origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function () {
var xhr = this;
var origArguments = arguments;
setTimeout(function () {
if (xhr.readyState === 1) {
origSend.apply(xhr, origArguments);
}
}, 1000);
};
Vairant that affects only jQuery AJAX requests:
$(document).ajaxSend(function (event, jqxhr, settings) {
var origXhrFunc = settings.xhr;
settings.xhr = function () {
var xhr = origXhrFunc();
var origSend = xhr.send;
xhr.send = function () {
var origArguments = arguments;
setTimeout(function () {
if (xhr.readyState === 1) {
origSend.apply(xhr, origArguments);
}
}, 1000);
};
return xhr;
};
});
In jQuery solution, you can easily attach handlers to jqxhr done/fail/progress events.
Upvotes: 2