sam999
sam999

Reputation: 115

Jquery multiple Ajax Request in array loop

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

Answers (2)

Senad Meškin
Senad Meškin

Reputation: 13756

I would solve your problem with recursive function.

Steps:

  1. Create a recursive function which will receive one parameter
  2. If array length is larger than 0 continue with the function body
  3. Shift array ( removes the first item from an array and store it into the variable)
  4. Call our function and execute AJAX call with provided parameters, and also pass our array
  5. When AJAX call is finished call our recursive function and pass our array to it

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

ibrahimyilmaz
ibrahimyilmaz

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

Related Questions