Javascript – continuously, respectively send requests to server

continuous

Sometime you may want to send requests continuously to server with one request each time ( like a foreach in PHP, or for x in array or .each in Ruby …). we have ‘for’ and ‘for .. in’ loop but it’s not smart enough to wait for an Ajax request to be responded. so it doesn’t help us to fulfill our target. what should we do to loop through array, send Ajax request to server with data from array element and wait for response before sending new request ?

I experienced this case several times and i have a small trick for it. you can call it an algorithm if you want (actually, i named it ‘left hand – right hand algorithm). see the below code

var todo = JSON.parse('<?php echo $todo ?>');
var total = <?php echo $urlcount ?>;
var counter=0;
var progressBar;
progressBar = new ProgressBar("results", {'width':'650px', 'height':'20px'});

function updateProgressBar(counter, total)
{
  var percent = counter/total * 100;
  percent = Math.ceil(percent);
  percent = percent < 100 ? percent : 100;

  progressBar.setPercent(percent);
}

function updateCurrentUrl(url)
{
  $('currenturl').innerHTML = url;
}

function finalAction()
{
  $('final').show();
  // redirect to previous page
}

Event.observe(window, 'load', function(){
  function left() {
    new Ajax.Request(
      '<?php echo Mage::helper('adminhtml')>getUrl("fpcwarming/adminhtml_index/ajaxload")?>',
      {
        method: 'post',
        parameters: {id: todo[counter]['id']},
        onLoading: updateCurrentUrl(todo[counter]['url']),
        onSuccess: function(response){
          updateProgressBar(++counter, total);
          if (counter < total) {
            right();
          }
          else {
            finalAction();
          }
        }
      }
      );
  }

  function right() {
    new Ajax.Request(
        '<?php echo Mage::helper('adminhtml')>getUrl("fpcwarming/adminhtml_index/ajaxload")?>',
        {
          method: 'post',
        parameters: {id: todo[counter]['id']},
        onLoading: updateCurrentUrl(todo[counter]['url']),
        onSuccess: function(response){
          updateProgressBar(++counter, total);
          if (counter < total) {
            left();
          }
          else {
            finalAction();
          }
        }
        }
        );
  }

  left();
});

As you can see, i supply this Javascript script with an array from PHP first. we will also need ‘total’ and ‘counter’ to control our custom loop. I defined a progressBar object to show current process of this continuous Ajax request call. Next 2 function is for updating the progress bar Next function is finalAction(). you can define action at the end of your loop here Ok, let’s start rocking with our next two big stars : left() and right() – i named it as left hand, right hand algorithm, still remember ? Left() and right() are almost identical at ajax request parameters. the only difference here is function call on success. in case counter doesn’t exceed total AKA size of array. left() will call right() on success. likewise, right() will call left() on success, this loop will be terminated when counter exceed total. at this point, we call finalAction(). I hope this description will give you a good overview of the trick i mentioned. have fun!! 😀