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:
- I = 0
- Success or Error
- I = 1
- Success or Error
Actual Result
But after I run the code the console.log returns logs in following order
- I = 0
- I = 1
- Success or Error
- 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.
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
asyncflag tofalse:P.S. You don’t need to manually increment
i, jQuery’s.each()can provide it: