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”.

$(".verify_me").each(function(index, element) {
	$.ajax({
		type: 'get',
		url: 'run_me.php',
		data: {
				var1	: var1,
				var2	: var2
			},
		success: function() {
			// do something
		}
	});
}

I was unaware that by default .load() performs asynchronous HTTP (Ajax) requests. What does this means? Asynchronous requests means 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.

$(".verify_me").each(function(index, element) {
	$.ajax({
		type: 'get',
		url: 'run_me.php',
		async: false,
		data: {
				var1	: var1,
				var2	: var2
			},
		success: function() {
			// do something
		}
	});
}

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.

Artigos Relacionados

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.

Botão Voltar ao Topo
João Clérigo - Photography
Fechar

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!