abhanan93
abhanan93

Reputation: 249

jQuery Ajax - Not working inside loop

I have been trying to sort this problem for 2 days. But things don't seem to be working for me.

The code I have attached is working fine outside the loop but when I use it inside the loop, it simply doesn't works the way I want and logs a empty array into the console.

On a side not, using "async: false" inside my ajax request makes the code work correctly and outputs the array completely fine in the console but as you know using "async: false" is deprecated and completely freezes UI until the request is not completed.

Any other solutions rather than setting async to false?

for (var i = 0; i <= splittedURLSLength; i++) {
            var extracted = extractUsername(splittedURLS[i]);
            postData = {'name' : extracted};
            ajaxRequest = $.when( $.ajax({
            url: "/check",
            type: "POST",
            data: postData
            })).then(function(returnedResponse) {
                if (returnedResponse == "1") {
                    resultsArray.push(extracted);
                }   
            });
}
console.log(resultsArray);

Upvotes: 0

Views: 634

Answers (3)

Tate Thurston
Tate Thurston

Reputation: 4660

Because AJAX requests are asynchronous, your console.log will fire before the first AJAX request comes back. This is how the event loop works in Javascript.

You need to move your logic into your success handler:

for (var i = 0; i <= splittedURLSLength; i++) {
        var extracted = extractUsername(splittedURLS[i]);
        postData = {'name' : extracted};
        ajaxRequest = $.when( $.ajax({
        url: "/check",
        type: "POST",
        data: postData
        })).then(function(returnedResponse) {
            if (returnedResponse == "1") {
                resultsArray.push(extracted);
            }
            if(i === splittedURLSLength){
               console.log(resultsArray);
            }
        });

Upvotes: 1

DIEGO CARRASCAL
DIEGO CARRASCAL

Reputation: 2129

Just another idea to solve it...

var resultsArray[]//Global or should be pass to the function...

myIterate(0);

function myIterate(idx){
    var i = idx;
    if (i < splittedURLS.length){
        var extracted = extractUsername(splittedURLS[i]);
        postData = {'name' : extracted};
        ajaxRequest = $.when( $.ajax({
        url: "/check",
        type: "POST",
        data: postData
        })).then(function(returnedResponse) {
            if (returnedResponse == "1") {
                resultsArray.push(extracted);
                myiterate(i++);
            }   
        });
    }
}
console.log(resultsArray);

Upvotes: 0

Shekhar Chikara
Shekhar Chikara

Reputation: 3822

The problem you are facing is because you are logging resultsArray into console before it gets filled with the values from the AJAX request. The following code will give you a brief idea on how to use the data from the response-

for (var i = 0; i <= splittedURLSLength; i++) {
        var extracted = extractUsername(splittedURLS[i]);
        postData = {'name' : extracted};
        ajaxRequest = $.when( $.ajax({
                          url: "/check",
                          type: "POST",
                          data: postData
                      })).then(function(returnedResponse) {
                          if (returnedResponse == "1") {
                              resultsArray.push(extracted);
                              showResults(resultsArray);
                          }   
                      });
}

function showResults(resultsArray) {
    console.log(resultsArray);
    //Process your resultsArray as per requirement.
}

Upvotes: 1

Related Questions