2
I need to run the search for cities only after I finish loading the states within select and capturing the ID
. I’m taking this ID
to send another Ajax that will popular the cities of this state within another select.
What’s happening is that before the first script popular the states, the continuation of the code ends up capturing the previously selected state and making the search for this state and not for what has just been chosen.
What I need is for the code to wait for the popular script the states.
Without knowing what it’s really for, I tried to use the done thinking that it would trigger the continuation of the script only when the other script ends of popular states.
$.ajax({
url: 'http://cep.republicavirtual.com.br/web_cep.php',
type: 'get',
dataType: 'json',
crossDomain: true,
data:{
cep: $('#cep').val(),
formato:'json'
},
success: function(res){
// Seleciona tipo de logradouro e logradouro do CEP.
$('input[name=endereco]').val(res.tipo_logradouro+' '+res.logradouro);
// Seleciona bairro do CEP.
$('input[name=bairro]').val(res.bairro);
// Seleciona o estado conforme valor recebido no json ...
// Dispara um trigger para carregar as cidades do estado ...
$("#estado option").each(function() {
$(this).prop('selected', false);
if ($(this).data("sigla") == res.uf) {
$(this).prop('selected', true);
$("#estado").trigger("change");
}
});
}
}).done(function(res){
$(this).prop('selected', false);
$("#cidade option").each(function() {
console.log($(this).data("cityname"));
if ($(this).data("cityname") == res.cidade) {
$(this).prop('selected', true);
}
});
});
You need to move the code that is inside the block
done
to the blocksuccess
. The blocksuccess
is executed when you get the return of the ajax call, which is where you want to execute the other part of the code.– Ricardo Pontual