Javascript how to know when a loop ends

1

Dear I have a web application in which I have a table with teachers who will belong to a group.

My problem is that I do not know how to warn that the group was recorded correctly and reload the page.

I do the following

function GuardoTodo(){
var variable_post=$("#grupo").val();    //<-el nombre del grupo
var claveingresado=0;  
/// Invocamos a nuestro script PHP
$.post("grabo-grupo.php", { variable: variable_post }, function(data){
/// Ponemos la respuesta de nuestro script en el DIV recargado
	$("#recargado").html("Guardando Grupo");	 
	claveingresado=data;  //<- ese el id del grupo guardado

    //recorro los maestros seleccionados
	$("#listamaestros li").each(function(){
		var variable_post=claveingresado+","+$(this).attr('id');
		$.post("grabo-grupo-docentes.php", { variable: variable_post }, function(data){
			/// Ponemos la respuesta de nuestro script en el DIV recargado
				$("#recargado").html("Guardando docente al grupo");	 
			});
	});
			location.reload();

});

}

the issue is that if there are for example 50 teachers in the group only record 11, because you do not have time to finish traversing the li, if I take the line location.reload (); record everything perfect, but of course the screen remains without cooling, what I would like to do is that when the loop finishes it recharges correctly. thanks

    
asked by Cristian 05.01.2018 в 23:53
source

1 answer

0

Hello! I hope this helps you:

function GuardoTodo(){
var variable_post=$("#grupo").val();    //<-el nombre del grupo
var claveingresado=0;  
/// Invocamos a nuestro script PHP
$.post("grabo-grupo.php", { variable: variable_post }, function(data){
/// Ponemos la respuesta de nuestro script en el DIV recargado
	$("#recargado").html("Guardando Grupo");	 
	claveingresado=data;  //<- ese el id del grupo guardado
    var totalMaestros = $("#listamaestros li").length;
    var procesadosMaestros = 0;
	$("#listamaestros li").each(function(){
		var variable_post=claveingresado+","+$(this).attr('id');

        //recorro los maestros seleccionados
		$.post("grabo-grupo-docentes.php", { variable: variable_post }, function(data){
			/// Ponemos la respuesta de nuestro script en el DIV recargado
				$("#recargado").html("Guardando docente al grupo");
                procesadosMaestros++;
                if(procesadosMaestros >= totalMaestros)location.reload();
 
			});
	});

});

}

Greetings!

    
answered by 06.01.2018 / 00:03
source