I am using asynchronous XMLHttpRequests to fetch data from an API in pure JavaScript for the chrome extension I am developing. Here is the code snippet:
function getInfo(url, callback) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
callback(xmlhttp.responseText);
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
I have some tabs that when clicked should trigger the XMLHttpRequest request like this
<div class="tab">
<button class="tablinks" id = "HN" onclick="getLinks(event)"><img src=https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Y_Combinator_Logo_400.gif/100px-Y_Combinator_Logo_400.gif></button>
<button class="tablinks" id= "Reddit" onclick="getLinks(event)"><img class = "logo" src=https://www.observepoint.com/wp-content/uploads/2015/03/reddit-129.png></button>
<button class="tablinks" id= "Github" onclick="getLinks(event)"><img class ="logo" src=https://static1.squarespace.com/static/56278c08e4b07be93cfbb3aa/t/57f1de373e00bef6ad3fc3bc/1475468903021/github-logo?format=100w></button>
</div>
function getLinks(evt) {
getInfo("https://hacker-news.firebaseio.com/v0/topstories.json", function(result) {
//do stuff
});
}
However, when I call the getLinks function, the content in HTML remains unchanged. I am wondering if it's possible to nest the callback function inside another function as I'm currently doing. Or maybe there's a different approach I should take? I want the API call to only happen when one of the three buttons is pressed and the retrieved links to be displayed on the HTML. Is there a more efficient way to handle asynchronous calls in vanilla JS based on specific user actions? I am fairly new to JavaScript.