Calling ajax within another

2

How do I expect to return an ajax to continue requesting another? I have 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 the two are running at the same time and error. I tried to use async but it is already obsolete and hangs my browser! How to solve?

    
asked by anonymous 28.09.2016 / 22:23

2 answers

2

You can create a promise, you can use then to execute the next ajax.

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>

Relatedquestion:#

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

    
28.09.2016 / 22:43
1

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);
  });
    
28.09.2016 / 22:44