1

I am trying below code to fetch some URLs in for loop and adding all data in text variable and after the for loop completion, I am trying to check for text but it says undefined seems like ajax call is still not completed.

var text; 
    for (i = 0; i < 4; i++) 
    {
           link=links[i];
            $.ajax({
            url: scriptLnks,
            crossDomain: true,
            dataType: 'text',
            success: function (result) 
            {
                 text+= result;
            }

         });
 }
alert(text);

I want it to be asynchronous only. please help.

vijay
  • 493
  • 5
  • 19
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Jun 22 '17 at 05:30
  • Possible duplicate of [How to wait until jQuery ajax request finishes in a loop?](https://stackoverflow.com/questions/20291366/how-to-wait-until-jquery-ajax-request-finishes-in-a-loop) – t.niese Jun 22 '17 at 05:35

1 Answers1

1

Try

var text="";
var n=4;
var i=0;
doRequest(i);
function doRequest(i)
      link=links[i];
         $.ajax({
            url: scriptLnks,
            crossDomain: true,
            dataType: 'text',
            success: function (result) 
            {
                 if(i<n){
                     text+= result;
                     i++;
                     doRequest(i);
                 }else{
                     alert(text);
                 }
            }

        });
 }

Hope this helps!

vijay
  • 493
  • 5
  • 19