Kuldeep Daftary
Kuldeep Daftary

Reputation: 621

Using ajax in .each() loop

I'm trying to use ajax in a loop of tr.

Heres my code :

var i=0;
$("tr").each(function() {
var row = datastring;
console.log("I = " + i);
$.ajax({
    type: 'POST',
    url: 'somelinkgoeshere.com',
    data: row,
    success: function(){console.log("Success")},
    error: function(){console.log("Error")}
});
i++;
});​

Expected Result

So I want events to be fired in order where console.log must return logs in following order:

  1. I = 0
  2. Success or Error
  3. I = 1
  4. Success or Error

Actual Result

But after I run the code the console.log returns logs in following order

  1. I = 0
  2. I = 1
  3. Success or Error
  4. Success or Error

So it means my ajax function is called after my each loop is complete. But I dont want the function to loop unless ajax request is compete.

Let me know if you need more explanation.

Thanks.

Upvotes: 0

Views: 6096

Answers (3)

Mortalus
Mortalus

Reputation: 10712

Use async=false.

Here is a quote from the jQuery documentation:

asyncBoolean Default: true By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the complete/success/err

or callbacks.

Upvotes: 1

A.M.K
A.M.K

Reputation: 16795

As mentioned mutiple times, Ajax is asynchronous. This means that other functions and code can run at the same time, the benefit of this is that the browser doesn't have to wait for a request to finish before continuing with the page JS execution. Imagine what it would be like if you have a dozen Ajax requests on a page and one server takes 30 seconds to respond...

However, if you still want to run the requests synchronously, you can set the async flag to false:

var i = 0;
$("tr").each(function() {
    var row = datastring;
    console.log("I = " + i);
    $.ajax({
        type: 'POST',
        url: 'somelinkgoeshere.com',
        data: row,
        async: false,
        success: function() {
            console.log("Success")
        },
        error: function() {
            console.log("Error")
        }
    });
    i++;
});​

P.S. You don't need to manually increment i, jQuery's .each() can provide it:

$("tr").each(function(i) {
    var row = datastring;
    console.log("I = " + i);
    $.ajax({
        type: 'POST',
        url: 'somelinkgoeshere.com',
        data: row,
        async: false,
        success: function() {
            console.log("Success")
        },
        error: function() {
            console.log("Error")
        }
    });
});​

Upvotes: 2

Marcus
Marcus

Reputation: 5447

You'd have to set async to false.

$.ajax({
    type: 'POST',
    url: 'somelinkgoeshere.com',
    async: false,
    data: row,
    success: function(){console.log("Success")},
    error: function(){console.log("Error")}
});

This is not the best thing to do though, as it may lock up the browser, and the whole point of AJAX is to be asynchronous.

Upvotes: 1

Related Questions