How to execute a code only after finishing another?

2

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);
            }  

        });                   

    });
    
asked by anonymous 20.10.2016 / 15:56

2 answers

1

You can use ajax async option to false, read more here: link

In this way the script expects the whole process to end in order to continue the code below.

Code sample with async:

$.ajax({
    url: 'http://cep.republicavirtual.com.br/web_cep.php',
    type: 'get',
    async: false,
    ...
    
20.10.2016 / 19:27
1

If what you need to do is not directly bound to the result of the AJAX call the ideal would be to put in a separate function:

success: function(res){

           // Faça o que tem que fazer

            minhaFuncao();
            });

        }

// fora da função que fez a chamada

function minhaFuncao(){
  // Faça o que quiser depois que acabou
}
    
20.10.2016 / 21:34