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.– Sam
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.
– Sam