I need to run the city search only after finishing loading the states within the select and capturing the ID
. I'm getting this ID
to send another Ajax that will populate the cities of this state within another select.
What is happening is that before the first popular script states, the continuation of the code ends up capturing the previously selected state and doing the fetch for this state and not for what has just been chosen.
What I need is for the code to wait for the script to populate the states.
I do not know what it really is for, I tried to use done thinking that it would fire the script continuation only when the other script ended up populating the states. / p>
$.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);
}
});
});