A jQuery Get() inside another jQuery get()

Asked

Viewed 311 times

1

I need to run a jQuery Get() inside another, but I’m not getting anywhere, just ignore the second Get() without returning what I need (the username of the second get()):

$.getJSON("https://api.mercadolibre.com/users/" + minha_id + "/order_blacklist?access_token=" + access_token, function(data){
	var employee_data ='';
	for (var i = 0; i < data.length; i++) {
		employee_data += '<tr>';
		$.getJSON("https://api.mercadolibre.com/users/" + data[i].user.id + "?access_token=" + access_token, function(valor){
			username = valor.nickname;
			employee_data += "<td>" + username + "</td>";
		});
		employee_data += '<td>' + data[i].user.id + '</td>';
		employee_data += '<td>' + data[i].user.blocked + '</td>';
		employee_data += '</tr>';
		$('#employeed_table').append(employee_data);
	}
});

  • There is a serious problem with your code. You are placing an asynchronous request within a code for, This is dangerous, it may never work your code this way.

2 answers

1

When making an asynchronous request you should wait for a response. If you place a request within a for, including a variable change (as in username = valor.nickname;), values will be scrambled and will not work the way you want.

You can solve this by making a request for looping, using a pointer and calling a function in repainting loop:

$.getJSON("https://api.mercadolibre.com/users/", function(data) {
   
   // cria um "for assíncrono", passando o ponteiro inicial '0', a variável 'data' e um 'callback'
   forAsync(0, data, function(employee_data){
    
    // após a função executar todas as requisições, será retornada a variável employee_data
    $('#employeed_table').append(employee_data);
    
   });
   
}); 

function forAsync(i, data, callback, employee_data = null) {
  
  if(employee_data == null) {
    employee_data = '';
  }
  
  if(data.length > 0) {
    
    employee_data += '<tr>';
    
    $.getJSON("https://api.mercadolibre.com/users/" + data[i].user.id + "?access_token=" + access_token, function(valor){
			
      var username = valor.nickname;
      
      employee_data += "<td>" + username + "</td>";
      employee_data += '<td>' + data[i].user.id + '</td>';
      employee_data += '<td>' + data[i].user.blocked + '</td>';
      employee_data += '</tr>';
      
      i++;
      
      if(i < data.length) {
        forAsync(i, data, callback, employee_data);
      }
      else {
        callback(employee_data);
      }
      
		});
    
  }
  else {
    callback(employee_data);
  }
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

It may not be the best way to fix the problem and there are probably better methods, but for this you will have to revise your code and run it for such.

  • 1

    It almost worked, but he injected only the first occurrence, debugei with console.log and is receiving the data correctly, but it seems that not the time to inject them in the gift in time, I’m trying to adapt with your tips, thanks for the help.

  • You are absolutely right. He was only taking a record because he had always set the variable employee_data as ''. I made the change, make sure it works!

  • Perfect, it was too much!!

0

Friend uses ajax that gets simpler:

$.ajax({
    type: "GET",
    url: api.mercadolibre.com/users/" + minha_id +"/order_blacklist?access_token=" + access_token,
    success: (response) => {
        $.ajax({
            type: "GET",
            url: api.mercadolibre.com/users/" + minha_id +"/order_blacklist?access_token=" + access_token,
            async: false,
            success: (response) => {    

            },
            error: (response) => {
              console.log('Sem sucesso');
            }
        });
    },
    error: (response) => {
      console.log('Sem sucesso');
    }
});

When you get back the first GET, you do another GET

  • Maycon thanks for the help, but here I fall into the same problem that is inside the For loop, even with Ajax of the same problem because the other Ajax be inside the loop

  • Friend puts one more property in your ajax, async: false, which will make your ajax synchronous then you will no longer have this problem.

  • @Mayconf.Castro, this maybe not a good idea.

Browser other questions tagged

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