Reputation: 115
How can make multiple ajax requests on by one i have a big array of data and i loop through that array and in every loop i need to make ajax request to server but i want to make request only when last request is finsihed
This is my code now:
// This is loop for BigData
length = BigArray.length;
for (i = 0; i < length; i++) {
token = BigArray[i][0];
name = titleCase(BigArray[i][1]);
ajaxRequest(token, name);
}
function ajaxRequest(token, title) {
$.post(APP_URL + "/message/send", {
"_token": Laraveltoken,
title: title,
token: token
}, function(data, status) {
//When Done start next request
});
}
Upvotes: 0
Views: 599
Reputation: 13756
I would solve your problem with recursive function.
Steps:
Code:
function myRecursiveFunction(myArray){
if(myArray.length == 0) return;
//remove first item of an array then store it into variable item
var item = myArray.shift();
//call our method which will execute AJAX call to server
ajaxRequest(item[0], titleCase(item[1]), myArray);
}
function ajaxRequest(token, title, myArray) {
$.post(APP_URL + "/message/send", {
"_token": Laraveltoken,
title: title,
token: token
}, function(data, status) {
//When Done start next request
}).always(function(){
//call our recursive function
myRecursiveFunction(myArray);
});;
}
Upvotes: 1
Reputation: 2335
You can use async.js for multiple asynchronous operation.
https://caolan.github.io/async/
Examples:
async.parallel([
function(callback) { ... },
function(callback) { ... }
], function(err, results) {
// optional callback
});
async.series([
function(callback) { ... },
function(callback) { ... }
]);
Upvotes: 0