0
I have the following question/problem: I have an ajax script that searches the zip code and fills some fields on the screen. One of them is the neighborhood.
In the sequence I need to use the result of this field to perform another search in ajax.
What is going on? When the second ajax call is held, the field input
neighborhood is not yet filled. IE, the url that is being triggered the value that should be filled, is not.
I tried to create a local variable to store this information so that I can use it in the second call, and the result is still null.
What I realized when I am on the page, at the end of the script the data is displayed on the screen, so only at the end of the process is the screen update and so the input
is still empty as I try to use it.
How to make the field be updated at the same time to associate a value to it and use in the same event?
Below is my script (only part of it:
if(validacep.test(cep)) {
//Preenche os campos com "..." enquanto consulta webservice.
$("#logradouro-destino").val("...");
$("#bairro-destino").val("...");
$("#cidade-destino").val("...");
$("#uf-destino").val("...");
//$("#ibge").val("...");
$('#info-cep').html('Logradouro');
//Consulta o webservice viacep.com.br/
$.getJSON("//viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados) {
if (!("erro" in dados)) {
//Atualiza os campos com os valores da consulta.
$("#logradouro-destino").val(dados.logradouro.toUpperCase());
$("#bairro-destino").val(dados.bairro.toUpperCase());
$("#cidade-destino").val(dados.localidade.toUpperCase());
$("#uf-destino").val(dados.uf.toUpperCase());
} //end if.
else {
//CEP pesquisado não foi encontrado.
//limpa_formulário_cep();
$('#info-cep').html('Logradouro ***CEP não encontrado ***');
}
});
// foco vai para o endereco
$('#logradouro-destino').focus();
var tipoItinerario = $('#tipo-itinerario').val();
$('#valor-itinerario').val(0.00);
if (tipoItinerario == 'K') {
// buscar distancia
var cepOrigem = $('#cep-origem').val();
var cepDestino = $('#cep-destino').val();
var url = '/calcular/' + cepOrigem + '/distancia/' + cepDestino;
$.getJSON(url, function(dados){
$('#distancia-destino').val(dados);
buscarValor(dados);
});
} else if (tipoItinerario == 'A'){
// esta chamada o campo #bairro-destino está nulo
var cliente = $('#cliente-id').val();
var url = '/buscar/' + $('#bairro-destino').val() + '/valor/' + cliente + '/bairro';
$.getJSON(url,function(dados){
$('#valor-destino').val(dados);
$('#valor-destino').maskMoney();
});
}
} .
Your second call getJSON is being called before completing the first. The solution would be: async: false, plus getJSON does not have async: false as an option. You would have to use ajax for this. $. ajax({ dataType: "json", url: url, date: date, Success: Success });
– Netinho Santos
Or move the second block inside the return of the first
$.getJSON()
– Leandro Angelo