2
Ajax
for (j=0; j < cidade_nome.length; j++) {
$.post('envia.php', {ano:ano, ano2:ano2, cidade: cidade_nome[j].value}, fnRetorno);
}
Function fnReturn
function fnRetorno(retorno)
{
teste.push(retorno);
console.log(j);
if (j == cidade_nome.length) {
soma(teste);
}
}
Complete Code
function soma(teste)
{
console.log(JSON.parse(teste));
}
function fnRetorno(retorno)
{
teste.push(retorno);
console.log(j);
if (j==cidade_nome.length) {
soma(teste);
}
}
for (j=0;j<cidade_nome.length;j++) {
$.post('envia.php', {ano: ano, ano2: ano2, cidade: cidade_nome[j].value}, fnRetorno);
}
Because ajax is asynchronous, the function fnRetorno
calls the sum function, before the last ajax result is placed in the array teste
.
Would have some way to ensure that the sum test function would only be called after ajax is run every time by loop?
SORRY, BUT YOU WANT HIM TO CALL AFTER EXECUTING ALL TIMES I MEAN... ONCE, OR EVERY TIME HE FINISHES EXECUTING THE REQUEST?
– Rafael Withoeft
Let him call the sum function, just once. I guess I didn’t make it clear,
– Rodolfo Oliveira
Explain better what you want to do with the request. What does the server do? What is the return?
– Oeslei
The request returns to the fnRelat function a JSON that must be placed in the array,for the Sum function to be generated a graph.
– Rodolfo Oliveira
But why run this request in a loop? Can’t you just pass the entire array at once and loop the server? For example:
$.post('envia.php',{ano:ano,ano2:ano2,cidades:cidade_nome}, fnRetorno);
– Oeslei
Then you can call the sum once after the for (and take it out of fnRetorno) and treat your array using $.each as you need it, isn’t that so? @Oeslei, your nomination is also quite interesting.
– Rafael Withoeft
@Rafaelwithoeft This is not possible with an asynchronous request. The function would be executed before the return of the server.
– Oeslei
@Oeslei Opa, sorry the slide did not remember this detail, well I only see two outputs, change the ajax to synchronous or send the logic to the server;
– Rafael Withoeft
The idea of @Oeslei would work, but my city_name comes from:"var city_name = $('#city option:Selected');",I would need to turn into an even correct array?
– Rodolfo Oliveira
@Rodolfooliveira Are you running a loop to traverse a string? Why?
– Oeslei
@Oeslei is not a string, I am using a 'component' which is a checkbox combo,and city_name receives an object with the selected options
– Rodolfo Oliveira
@Rodolfooliveira, you can then use something like $.each to scroll through its values forming an array and then send it to the server, or swap its component and let jquery take care of it for you example:
var cidades = []; //Percorre tudo o que está selecionado em cidades $('#cidades :checked').each(function(i) { 
 cidades[i] = $(this).val(); 
});
– Rafael Withoeft