//A function that handles multiple AJAX requests
function AjaxMultiple(ajaxArray, callback){
//Set the callback
this.callback = callback;
//A function that handles the callback from the requests
this.CallbackHandler = function(){
this.amount -= 1;
if (this.amount === 0) this.callback();
}
//A variable that is used to indicate how many requests are remaining to be completed
this.remain = ajaxArray.length;
for (var i = 0; i<this.remain; i++){
//Current object
var ajax = ajaxArray[i];
//Note: _this is used as the property "this" changes within $.post and $.get
var _this = this;
//Specify file directory (optional)
ajax['name'] = "php/"+ajax['name']+".php";
if (ajax['parameters']){
//Handle post request
$.post(ajax['name'], ajax['parameters'], function(xhr){
ajax['callback'](xhr);
_this.CallbackHandlerl();
});
} else {
//Handle get request
$.get(ajax['name'], function(xhr){
ajax['callback'](xhr);
_this.CallbackHandler();
});
}
}
}
//Example usage
//Ajax array containing 2 requests, one GET and one POST
var ajaxArray = [
//A GET request that obtains the current server time
{
name:"serverTime",
callback:function(xhr){
console.log("The current server time is "+xhr);
}
},
//A POST request that obtains the user email from the userId
{
name:"userEmail",
params:{
userId: 34
},
callback:function(xhr){
console.log("Your email is "+xhr);
}
}
];
//Actual call to function
new AjaxMultiple(ajaxArray, function(){
console.log("All tasks completed");
});
/*
Output:
==================================
The current server time is 12:05
Your email is xxxxxxx@gmail.com
All tasks completed
==================================
*/