-1

I am using asynch xmlhttprequests to get data from an API in vanilla Javascript for the chrome extension I am making like this

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 I want them to make 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
  });  
}

When I am calling the getLinks function, the stuff that I do to change the HTML never changes. My question is, is it possible to put the callback function inside of another function like I am doing? Or am I approaching it the wrong way? I want it so that only when I press one of the three buttons it retrieves links from the API and puts them in the HTML. Is there a better way of making asynch calls in vanilla JS only happen during a specific action. I am pretty new to JS.

1 Answers1

0

My question is, is it possible to put the callback function inside of another function like I am doing?

Yes.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205