Abhay Kumar
Abhay Kumar

Reputation: 15

Jquery Ajax wait for asynchronous response

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.

Upvotes: 1

Views: 623

Answers (1)

vijay
vijay

Reputation: 492

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!

Upvotes: 1

Related Questions