I was having a big problem using .load() within .each() loop. The problem was that I wanted the each .load() to iterate one after the previous has finished, and not all iterations to run all at the “same time”.
<br />$(".verify_me").each(function(index, element) {<br /> $.ajax({<br /> type: 'get',<br /> url: 'run_me.php',<br /> data: {<br /> var1 : var1,<br /> var2 : var2<br /> },<br /> success: function() {<br /> // do something<br /> }<br /> });<br />}<br />
I was unaware that by default .load() performs asynchronous HTTP (Ajax) requests. What does this mean? Asynchronous requests mean that the requests are made one after another, but the script will not wait to see if the request was successful or not, and script are not synced with browser operations.
An easy way to solve this problem is to turn .load() to work synchronously, forcing the script to finish. Use the option async: false, it is set to true by default.
<br />$(".verify_me").each(function(index, element) {<br /> $.ajax({<br /> type: 'get',<br /> url: 'run_me.php',<br /> async: false,<br /> data: {<br /> var1 : var1,<br /> var2 : var2<br /> },<br /> success: function() {<br /> // do something<br /> }<br /> });<br />}<br />
You should be mindful that cross-domain requests and dataType: “jsonp” requests do not support synchronous operations and, synchronous requests may temporarily lock the browser, disabling any actions while the request is active.