How to save and retrieve multiple returns from an AJAX request in a loop?

Asked

Viewed 85 times

0

Gentlemen, good night, sir. I am trying to accomplish the following task, I am sending via AJAX to another page 3 cep’s, when I get there I give only an echo of the sent cep to know that arrived, this echo enters the success check where I test the validity, that is, different from empty and enters the next action. When I give only one Alert(data) it shows the ceps one at a time according to loop, but if I say to perform an increment each time and already out of the loop I give an Alert of n then the Alert results in 0 (zero).

Excuse my ignorance if the question is silly or I’m making some trivial mistake.

The purpose of this test is that the idea is to arrive at the following solution, a db that contains data needs to receive data from csv as long as this data no longer exists in the database, soon thought of the following solution, the page one loads the csv, calls ajax, ajax calls the php page responsible for the check and Insert and whenever it returns 1 (um) ajax makes an increment, why this, to be able to inform the user that of X records imported N were inserted.

function testeAjax() {

var cep = ['cep 01', 'cep 02','cep 03'];
var n = 0;
for(var c=0 ; c < cep.length ; c++){

    jQuery.ajax({
        type: "POST",
        url: "./_inc/controler/uploadArquivosControle.php",
        data: { acao:'insertUpdate', cep: cep[c] },
        success: function( data ){

            if(data!==''){
                n++;
            }

        }

    });

}
alert(n);
}

<?php
$acao = $_REQUEST['acao'];

$dao = new UploadArquivosDAO();

switch ($acao) :
    case 'insertUpdate':

        $cep      = addslashes($_POST['cep']);
        echo $cep;
    break;
endswitch;
  • The problem is that when you get on the line alert(n); Ajax has not yet been processed because it is asynchronous.

  • Imagine the comparative situation where Ajax is 3 emails that you send to a friend and expect a response from each message sent. The answers do not see at the same time and when arriving at the line of Alert you have not had any answer yet. That is, your friend will still have to open his email, read the message and reply, and it does not happen at the same time that you sent the messages.

1 answer

0

As I had commented, Ajax is asynchronous. The code within the for is called but the alert which comes soon after is executed immediately before Ajax gives reply.

In this case the correct would be to use the function recursively and go calling each Ajax after the previous return the request in the success. As in the example you want to make 3 Ajax requests (array size cep), make a if checking whether the variable counting the number of requests is smaller than the size of the array: if it is smaller, you make a new request; if not, triggers Alert.

Create the variable that counts requests outside the function using a specific name for the case to not conflict with other possible variables that you use (in this case I used num_cep). This variable starts with the value 0. At each success you will increment the variable and call the function again. When the value of the variable is equal to the number of items in the array cep, the if will fall into the else firing the Alert with the number of requests made that returned !== '' in the variable inseriu:

var num_cep = 0;
var inseriu = 0;
function testeAjax() {

   var cep = ['cep 01', 'cep 02','cep 03'];
   var cep_length = cep.length;

   if(num_cep < cep_length){

       jQuery.ajax({
           type: "POST",
           url: "./_inc/controler/uploadArquivosControle.php",
           data: { acao:'insertUpdate', cep: cep[num_cep] },
           success: function( data ){
               if(data!==''){
                   inseriu++;
               }
               num_cep++;
               testeAjax();

           }

       });

   }else{
      alert(inseriu);
      // reseta as variáveis
      num_cep = 0;
      inseriu = 0;

   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.