Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain ajax calls using plain javascript

I've looked for the answers but couldn't find anything with plain Javascript. What would be the appropriate way? I tried to use the same approach repetitively but it didn't work. How can I solve this with pure Javascript?

       function someFunction(){ 
    var url = "someUrl";
    var xmlhttp = new XMLHttpRequest ();
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
    xmlhttp.onreadystatechange = function (){
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200){  
        obj = JSON.parse(xmlhttp.responseText);
      length = obj.ajax.length;
        for(var i = 0; i < length; i++ ){
            try{
              var someVar = obj.ajax.elements[i].id; 
              var url2 = "someOtherUrl"+someVar+"/features";
              var xmlhttp = new XMLHttpRequest ();
              xmlhttp.open("GET", url, true);
              xmlhttp.send();
              xmlhttp.onreadystatechange = function (){
              if (xmlhttp.readyState == 4 && xmlhttp.status == 200){  
              obj2 = JSON.parse(xmlhttp.responseText);
              length2 = obj2.ajax.length;
              for(var j= 0; j < length2; j++){ 
              var elementNames = obj2.elements[j].name; 
               }
             }
            }
           }
          }
         }
like image 245
ricster Avatar asked Sep 01 '26 12:09

ricster


1 Answers

You can call that someFunction() recursively.
To do so, You just have to invoke that same function after 200 ok response.
In following code I've added a restriction to return form recursive callback stack after a fixed amount of requests in chain.

EDIT : for multiple urls

callDone  = 0;
urls = ['http://url1','http://url2','http://url3'];
totalCall = urls.length - 1;

function someFunction(){
  
  //Edit: > Fetch url from array
   var url     = urls[ callDone ] ;
   var xmlhttp = new XMLHttpRequest ();
       xmlhttp .open( "GET", url, true);
       xmlhttp .send();
       xmlhttp .onreadystatechange = function ()
       {
          if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
              //your stuff with response... 
      
              if( callDone < totalCall ){
                callDone++;
                someFunction();
              }
              else{
                  return;
              }
           }
       }
}
like image 113
Jimish Fotariya Avatar answered Sep 04 '26 01:09

Jimish Fotariya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!