Currently, I am in the process of creating a replica of Hacker News using vanilla JavaScript.
In my JavaScript code snippet:
var apiResult = document.getElementById("apiResult");
function apiContent() {
var url_end = ' https://hacker-news.firebaseio.com/v0/topstories.json?
print=pretty';
var apiCall = new XMLHttpRequest();
var links = [];
apiCall.onload = function() {
if(this.status == 200) {
var apiData = JSON.parse(apiCall.responseText);
for( var i = 0; i < apiData.length; i++){
var url = 'https://hacker-news.firebaseio.com/v0/item/' ;
var c_url = apiData[i] + '.json?print=pretty';
var final_url = url + c_url;
links.push(final_url);
}
for(var j = 0; j < links.length; j++) {
var a = links[j];
var secondRequest = new XMLHttpRequest();
secondRequest.onload = function() {
var secondData = JSON.parse(secondRequest.responseText);
console.log(secondData);
}
secondRequest.open('GET', a, true);
secondRequest.send();
}
}
else {
console.log('Unable to fetch data');
}
}
apiCall.open("GET", url_end, true);
apiCall.send();
}
The first API call 'url_end' provides the ID of the top 500 stories, returning only the ID. To retrieve the content related to each story ID, I'm making a second AJAX call with an updated URL containing the ID. However, this approach is not functioning as expected.
What adjustments should I make to ensure its proper functionality?