Is it possible to encase the callback function of an asynchronous xmlhttprequest within another function?

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.

Answer №1

Could the callback function be nested within another function, as I am currently doing?

Absolutely.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Grab the div, position it accurately, and initiate an ajax call

So many tasks on my plate, but let's prioritize. Within a <div class="showcase">, I have numerous <div class="game"> elements, each with an onclick="addpop('delpopup.php?id=something&pos=somethingelse&box=image')" Does ...

Error: The res.end function is not recognized within the passport npm package

Help Needed: I am encountering this error and unable to resolve it. Can someone please check it out? TypeError: res.end is not a function at allFailed (C:\Users\sam\OneDrive\desktop\WebDevPractice\secret-files\node_mo ...

What could be the reason for webpack not making jQuery available as a global variable?

For my current project, I am utilizing several npm modules by integrating them using yarn and webpack. These essential modules include jquery, bootstrap3, moment, jquery-tablesort, jquery-ujs, bootstrap-select, and livestamp. Some of these plugins require ...

When JSONP is used in cross-domain AJAX calls, it retrieves plain JSON data

I am facing an issue with an API that I need to integrate. The API provides JSON data, but as it involves a cross domain AJAX call, I have to utilize jsonp. $.ajax({ type: "GET", url: url + query, ...

PHP function json_encode() is causing an issue by returning an "Undefined" value

I'm working on a PHP project where I am creating an array and using json_encode() to convert it into JSON before retrieving it with $.getJSON. However, I am encountering an issue where it returns Undefined when trying to send all the data at once. Int ...

Upon the second visit, Bootstrap popover functions as expected

After creating a website on SharePoint using Bootstrap and populating the content with JavaScript, I encountered an issue with popover functionality. Oddly enough, the popover only works after refreshing or reloading the page with F5. Strangely, popovers ...

Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'. I attempted to replicate this in jsFidd ...

My goal is to design a dynamic textbox for a website that allows users to customize the text in any format they desire

I want to create a versatile textbox on my website that allows users to change the text format as they desire. Unfortunately, I am facing some issues with implementing this feature. Here is the code I have developed so far. <body> <h1>< ...

The input values passed to "onChange" are not compatible with "NativeSyntheticEvent<TextInputChangeEventData>"

I'm fairly new to React Native and encountered an issue while trying to implement the following code snippet: <TextInput style={styles.input} onChange={(text) => setPontoValue(text)} /> This error message ...

Challenges with Implementing RTL Support in React Material UI Pagination Component

I've been trying to switch my pagination layout from left-to-right (ltr) to right-to-left (rtl), but the arrows are not aligning correctly in the rtl version. I attempted to use a solution provided here, but unfortunately, it didn't work as expec ...

Subdivisions within a larger division

Initially, I have a page layout divided into four sections resembling something like this. My attempt has been to insert three "inner sections" within each main section as demonstrated here. I am aiming to achieve the following result but I am unsure of ...

Updating data dynamically in pug front end using Axios call response

I am currently working on implementing a search form along with an endpoint to retrieve the results. Once I receive the response, I want to dynamically add a div element to my pug/jade file to notify the user whether an order has been found or not. Here i ...

States have the autonomy to set their own right-side menu alongside the constant presence of the left menu

Looking for a solution where my left side menu remains consistent across all states, but each state can have its own optional right side menu with custom content. The current approach involves creating a separate directive for the left side menu that each ...

Reloading a CodeIgniter page following an AJAX click action

I am currently facing an issue with my PHP CodeIgniter function code that is called by a jQuery AJAX function: $this->load->library('session'); $this->load->helper('url'); $ids = $_POS ...

What are the steps to utilizing the $document service in AngularJS?

I am a complete beginner when it comes to AngularJS and JavaScript in general, and I find myself a bit confused about the usage of $document. From what I understand, $document provides access to some JQuery functions. So, if I want to remove an element tha ...

Attain the ability to distinguish errors in Promises

Context In my project, I have implemented a REST API that interacts with MongoDB using Node.js and Express. The issue at hand involves handling errors based on different scenarios when making requests to the NoSQL database. Challenge The current impleme ...

Is there a way to avoid getting a 404 error in Express when using multiple static directories?

I am working on serving files from two different folders to keep my admin and client content separate. The code I have set up initiates the two folders, but when Express looks for a file like example.css, it first checks the /static directory. If it doesn ...

How to handle a bad request response in AJAX while reading JSON result

If the user doesn't fill out the form correctly, I want to send an error message via ajax. Here is how I send the response to the browser using ajax: if($bo){ header('HTTP/1.1 400 Bad Request'); header('Content-Type: applicati ...

Caution: It is important that every child within an array or iterator is assigned a distinct "key" property

As a new developer in ReactJS, I have created a table using ReactJS on the FrontEnd, NodeJS on the BackEnd, and MySQL for the database. My goal is to retrieve data with a Select request on the table. For my frontend: class ListeClients extends Component ...

Well-structured JSON output generated from a string

Source Data: Dialogflow Response : id: \"9f912860-e5c6-4e57-934b-8639595b947f-d571b79b\"\nlang: \"en\"\nsession_id: \"3e22f813-79bb-b29a-1def-4c5e4ce4b23b\"\ntimestamp: \" ...