Example AJAX Queue helper
Sequential AJAX helper
JavaScript
// EXAMPLE MAIN CODE (best to put at end, but I put it here because it's easier to spot it!)
var Q = new AQ();
function ajax_calls() {
Q.add('ajax_call("file_name1", "a=A&b=B")');
Q.add('ajax_call("file_name2", "a=A&b=B")');
Q.add('ajax_call("file_name3", "a=A&b=B")');
Q.add('allDone()');
Q.start();
}
// EXAMPLE AJAX POST
function ajax_call(myFile, myData) {
$.ajax({
type: "POST",
url: myFile,
data: myData,
success: function(data) {
log('callback '+i);
//call the next in line
$(document).dequeue('myAjaxQueue');
}
});
/* $.ajax({
type: "POST",
url: myFile,
data: myData,
success: function(response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus);
},
complete: function() {
Q.doNext();
}
}); */
}
// EXAMPLE FUNCTION TO SHOW EVERYTHING HAS COMPLETED
function allDone() {
console.log("All Done");
}
// MY OWN QUEUE HELPER
function AQ() {
// QUEUE HELPER
if (this instanceof AQ) {
var q = [];
var running = false;
this.add = function (stringExec) {
if ((q.length == 0) && (running)) {
return eval(stringExec);
} else {
q.push(stringExec);
}
};
this.doNext = function () {
return eval(q.shift());
};
this.start = function () {
if (q.length == 0) return alert("Cannot start because Q is empty");
if (!running) {
running = true;
var _this = this;
return setTimeout(_this.doNext(), 10);
}
};
} else {
return new AQ();
}
}