How to execute one code only after finishing another?

Asked

Viewed 1,489 times

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

        });                   

    });
  • 3

    You need to move the code that is inside the block done to the block success. The block success is executed when you get the return of the ajax call, which is where you want to execute the other part of the code.

2 answers

1

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

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
}
  • It is directly connected. The second step depends on information from the first.

  • then you put the code next to the rest on sucess

1

You can use the option async ajax as false, read more here: http://api.jquery.com/jquery.ajax/

This way the script waits the whole process to finish to give continuity to the code below.

Example of code with async:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.