BlogProgramming

Invoking a jQuery function after .each() has completed

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.

Related Articles

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *

Este site utiliza o Akismet para reduzir spam. Fica a saber como são processados os dados dos comentários.

Back to top button
João Clérigo - Photography
Close

AdBlocker Detetado
AdBlocker Detected

Por favor ajude este website permitindo a visualização de alguns anúncios. Obrigado. Please help this website allowing the view of some advertising. Thank you!