user2224250
user2224250

Reputation: 251

JQuery: How to callback each loop after completion of ajax call?

How to callback each loop after completion of ajax call.

Please find my code as follows.

Story:

Let us assume I have 3 values X,Y,Z. Firstly, I am taking X value, sending to django views and their using requests module for getting some info and pushing to the div class push_new_info_here, in the next Iteration I have to take Y value. How to do ? please note: Previous ajax call should be succeeded .

Final word: I am collecting all the info of (X,Y,Z), then merging using python and pushing to the div class push_new_info_here

window.onload = function() {

  $.each(["X","Y","Z"], function( index, value ) {

      $.post('/find/'+value+'/',{},function(data){
          $('.push_new_info_here').empty();
          $('.push_new_info_here').html(data);
      });

  });

};

Upvotes: 1

Views: 105

Answers (2)

wolffer-east
wolffer-east

Reputation: 1069

try wrapping the call in a function, then recursing through the array using the AJAX .done method. For example

window.onload = function() {
  recursiveAjax(["X","Y","Z"])
};

function recursiveAjax(values){
  //basic error testing
  if (typeof values == "undefined" || values.length == 0) return false
  var value = values.pop();
  $.post('/find/'+value+'/',{},function(data){
    $('.push_new_info_here').empty();
    $('.push_new_info_here').html(data);
    recursiveAjax(values)
  });
}'

EDIT: To avoid destroying the array we can send a cloned copy through to the function. For example:

window.onload = function() {
  var tempArray = ["X","Y","Z"]
  recursiveAjax(tempArray.slice())
};

Upvotes: 1

mplungjan
mplungjan

Reputation: 178422

Like this - use .append if you want to see the data or change the timeout to something long enough for the user to see:

var arr = ["X","Y","Z"],cnt=0;

function postIt() {
  if (cnt >= arr.length) return; // stop
  $.post('/find/'+arr[cnt]+'/',{},function(data){
      $('.push_new_info_here').empty().html(data); // or .append
      cnt++; 
      postIt(); // or setTimeout(postIt,3000); // give server a breather
  });
}


$(function() {
  postIt();
});

Upvotes: 3

Related Questions