How to call an ajax inside another?

Asked

Viewed 2,611 times

2

need to call another ajax request within a condition. But the outside ajax does not wait for the inside to finish. Example: I wear this

 $.ajax({
                        type: "GET",
                        url: "MINHA_URL",
                        success: function (e) {
                        if(e == 'erro'){
                           $.ajax({
                               type: "GET",
                               url: "MINHA_SEGUNDA_URL",
                               success: function (f) {
                                  IMPRIMIE ALGUMA COISA
                               }
                       .....

The problem is that it does not run correctly. How to proceed?

  • 1

    I don’t know which version of jQuery you are using but the common is to use the done to execute something when the request is actually completed.

2 answers

0

Mas o ajax de fora não espera o de dentro terminar para finalizar. 

It doesn’t wait because it’s asynchronous requisitions. Set in ajax call the option async: false

  • 1

    The problem is that {async: false} is already obsolete in newer versions of jquery!

0


    $.ajax({
    url: 'MINHA_URL',
    type: 'post',
    data: {
        html: 'Teste 1'
    },
    success: function(returnhtml) {
        $("#result").append($('</p>').html(returnhtml));
        $.ajax({
            url: 'MINHA_URL',
            type: 'post',
            data: {
                html: 'Teste 2'
            },
            success: function(returnhtml) {
                $("#result").append($('</p>').html(returnhtml));
            }
        });

    }
}); 

Resultado : <div id="result"><p>Teste 1</p> <p>Teste 2</p> </div>

Practical example: http://jsfiddle.net/qz02oukw/

Browser other questions tagged

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