2
I have a problem with calls in AJAX, I need to make more than one call in AJAX to store in different variables and in that I can treat them.
I’m just having trouble with AJAX’s ASYNC, because it’s taking too long to load the information from the Apis I call.
I’ve tried everything until I put one AJAX call inside another, but that’s not correct and it didn’t work because when leaving the second Success of the second call the value of the variable is lost.
Could someone help me how to do this otherwise?
My code below:
<script type="text/javascript">
var vUsers;
var vAlbums;
var length;
$(document).ready(function() {
$.ajax({ url: 'https://jsonplaceholder.typicode.com/users',
async: true,
success: function(data1) {
vUsers = data1;
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
return false;
}
});
$.ajax({url: 'https://jsonplaceholder.typicode.com/photos',
async: true,
success: function(data2) {
vAlbums = data2;
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
return false;
}
});
var table = document.getElementById('table');
function contaAlbums(lineId) {
length = 0;
vAlbums.forEach(function(album) {
if (album.userId == lineId) { alert(lineId + ' ' + album.userId);
length++;
}
});
return length;
};
vUsers.forEach((line) => {
var lineId = line.id;
var tr = document.createElement('tr');
var username = document.createElement('td');
var name = document.createElement('td');
var email = document.createElement('td');
var city = document.createElement('td');
var tdAlbums = document.createElement('td');
alert(lineId);
var albumCount = contaAlbums(lineId);
username.innerText = line.username;
name.innerText = line.name;
email.innerText = line.email;
city.innerText = line.address.city;
tdAlbums.innerText = albumCount;
tr.append(username, name, email, city, tdAlbums);
table.append(tr);
});
});
</script>
I need to pick up various information to be able to present in a table as image below:
you are trying to use the value of
vUsers
to make a foreach before waiting for the async call to return. It would be interesting to move this to a Function and call that Function onsuccess
from the first ajax, just after setting the variablevUsers
– Ricardo Pontual
the second problem is that in the code we use the
vUsers
, tbm needs the value ofvAlbuns
, which is another name of another async call, that is, you need this code to be executed when you return both calls. For this you can use the$.when(
, which receives a list of files (would have to put both ajax calls in a Function) or use tbmPromise.all(
who has the same idea, which includes an answer below– Ricardo Pontual