Call ajax inside another

Asked

Viewed 700 times

3

How to wait for the return of an ajax to continue the requisicao of another? I got the following:

    $.ajax({
        type: "GET",                                
        url: 'http://uma_url_qualquer.com',
        success: function (e) {
            var item = f.items; 
           //AQUI A OUTRA CHAMADA
            $.ajax({
                 type: "GET",                               
                 url: 'http://uma_url_qualquer.com',
                 success: function (f) {
                 }
           });
          //AQUI TERMINA          
        }
    }); 

The way these two run at the same time and error. I tried to use async but it is already obsolete and crashes my browser! How to solve?

  • 3

    As you have it in the code is a valid option. What does not work in this template?

  • I use a value taken in the first to use in the second. But the way the first executes all and only then the second executes.

  • 4

    It is correct that one only executes after the other and it is possible to use data from the first in the second, but not the other way around. One thing I don’t understand is why var item = f.items; before the second call when f is an argument of the second and not of the first.

2 answers

3

You can create a promise, you can use the then to run the ajax prox.

Example:

function meuAjax() {
  return $.ajax({
    type: "GET",
    url: 'https://httpbin.org/get',
    success: function(e) {
      console.log('Executou 1');
    }
  });
}

meuAjax().then(function() {
  $.ajax({
    type: "GET",
    url: 'https://httpbin.org/get',
    success: function() {
      console.log('Executou 2');
    }
  });

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

Related question: Ajax/Jquery - How to know if a request has been completed?

Very important detail, you are using the return of the second ajax in the first, and this is not possible, so the var item = f.items; is accessible only in the second ajax.

  • 2

    Promises are a good option (maybe better than the AP) but I don’t see that the problem here.

2

Try running in sequence using $.when:

  $.when(
    $.ajax({ // Primeira a ser executada
    url: 'http://uma_url_qualquer.com', 
    type: 'GET',      
    success: function(data){     
            resultado1 = data;                  
    }           
  }); 

  $.ajax({ // Segunda a ser executada
    url: 'http://uma_url_qualquer.com', 
    type: 'GET',      
    success: function(data){                          
        resultado2 = data;     
    }           
  }); 

  ).then(function() {
    $('#div1').html(resultado1);
    $('#div2').html(resultado2);
  });

Browser other questions tagged

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