Loop with php call wait until it finishes executing in each iteration

0

Dear, I do not know how to solve this, I have a json that I receive from php in the response variable, and what I want is to go through it as I do in the for, and in turn call another php that takes a little while to respond, the The issue is that I want you to wait for me to finish executing each php call in the for, how should I use it correctly with callback I guess? but I do not understand how to do. THANK YOU!

var response = JSON.parse( ajax_request.responseText );
    // La variable response ahora contiene un objeto con los datos recibidos
        //alert (response.length);
        for (var i in response){
            var aqueMaestra = response[i].maestra;
            //aviso por mails---------------------------------
            var variable_post=ElDocumentoES+","+aqueMaestra;
            $.post("aviso-docentes.php", { variable: variable_post }, function(data){
                $("#poptexto").html("Enviando mail a "+response[i].nombre);
            });

            if(i >= response.length-1)location.reload();
        }
    
asked by Cristian 24.01.2018 в 00:57
source

1 answer

0

Using an ajax inside a loop is a bad idea, you should choose to use a recursive method:

//Data del json en array
var response = JSON.parse( ajax_request.responseText );
//Cantidad de elementos del array
var cantidad = response.length;

//Funcion que realiza el envio
function  notifica(indice){

if(indice < cantidad){
    //Muestro el texto
    $("#poptexto").html("Enviando mail a "+response[indice].nombre);
    //Preparo variables a enviar
    var obj ={
        variable:variable_post
    };
    //envio la peticion
    $.post("aviso-docentes.php",obj)
    .done(function(resp){
        //Llamo de nuevo a la funcion si hay más parametros en el array
        notifica(indice+1);
    })
    .fail(function(err){
      $("#poptexto").html("Email no enviado a "+response[indice].nombre);
    })
}else{
    $("#poptexto").html("Todos los Email han sido enviados"
}
}

//ejecuto la función
notifica(0);

In this way the function is going to execute itself with each positive request of the ajax in an orderly manner, you can adapt it to your code. Greetings

    
answered by 24.01.2018 / 03:33
source