Sending asynchronous requests to handle data within various functions based on different links

I'm currently facing a major roadblock when it comes to resolving my issues with callbacks. I've gone through resources like How to return value from an asynchronous callback function? and How to return the response from an Ajax call?, among several others. While the latter was helpful for a different problem, I find myself struggling to adapt it to my current situation. It's possible that my approach is fundamentally flawed rather than just being inexperienced, which can be quite frustrating.

The core of my issue lies in the fact that I need the JSON result not only returned to a single callback function but also accessible by various functions corresponding to different events. For example:

Clicking on linkOne should trigger ajaxReq + getJsonData, followed by calling functionOne with the result as an argument

Clicking on linkTwo should also do the same with functionTwo

And clicking on linkThree should work similarly with functionThree

Can't we achieve this using link.onclick definition? Why does something like this not work:

linkThree.onclick = functionOne(getJsonData);

Below is an excerpt of my code:

function ajaxReq() {
    var request = new XMLHttpRequest();
    return request;
}

function getJsonData() {
    var request = ajaxReq();
    // Code omitted for brevity
    return myJsonArray; // This is where I'm facing issues
} 

function functionOne(myJsonArray) {
    var myJsonArray = getJsonData(); 
    // The above line doesn't work as expected
}

If invoking `ajaxReq()` inside `getJsonData()` returns the desired result, why doesn't the similar invocation in `functionOne` yield the same outcome?

Any assistance on how to tackle this would be highly appreciated. (Note: Preferably looking for a solution in pure JavaScript without relying on jQuery.)

svs

Answer №1

According to the information provided in the specified links, it is not possible to directly return a value from an asynchronous call and use it in a synchronous function call. However, there is a workaround for this situation -

One solution is to assign all onclick listeners a common function.

link1.onclick = someCommonfunction;
link2.onclick = someCommonfunction;
link3.onclick = someCommonfunction;

This common function can be defined as shown below. It will handle the json data in the callback function and allow you to pass that data to any other function.

function someCommonfunction(e) {
    var callback = function(jsonData) {
        var myJsonArray = jsonData; 
        // Perform conditional checks here and call different functions based on the conditions
    };  
    getJsonData(callback);    
}

The code for getJsonData has been modified to ensure that it calls the callback function with the response data.

function getJsonData(callback) {
    var request = ajaxReq();
    request.open("GET", "/myJSON.json", true);
    request.setRequestHeader("content-type", "application/json");
    request.send(null);
    request.onreadystatechange = function() {
        if (request.readyState === 4) {
            if (request.status === 200) {
                var myJsonString = JSON.parse(request.responseText);
                var myJsonArray = myJsonString["An Array in myJSON.json"];              
                callback(myJsonArray);              
            }
        }
    } // onreadystatechange
} // getJsonData

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

The DataTable is encountering difficulties with processing JSON data retrieved from the database

Setting up a datatable on my website has been quite the challenge. I came across a table that I wanted to use here, but converting it to fit my needs has not been successful. Currently, the table is not populating with rows from a database table and I&apos ...

What methods and technologies are accessible for executing JavaScript through PHP?

Are there any frameworks or tools available to execute JavaScript from PHP? Is there a similar project like the Harmony project for PHP? I am interested in running JS unit tests (or even BDD) directly from PHP, as demonstrated in this post (for Ruby). Am ...

Utilizing dynamically assigned ng directives in my unique custom directive

I'm in the process of creating a customized table element that looks like this: <datatable items='tableItems' columns='columnsConfig' /> Here, 'tableItems' represents my array of items and 'columnsConfig&apos ...

Creating a new row in a Tabulator component in React and retrieving the data

I have incorporated the react-tabulator library into my project and I am looking for guidance on how to dynamically add new rows once the tabulator has been rendered. Ideally, I would like to include a button below the tabulator that enables users to add a ...

Creating a stylish zebra pattern using JCrop on the cropping window

Lately, while using jquery jcrop, I've noticed a peculiar design appearing on the cropping window. The details of this pattern are unclear to me. What could be the reason behind the zebra-like pattern visible on the cropping window? Is there any spec ...

The Typescript module in question does not contain any exported components or functions related to

I've encountered an unusual issue while working on a React, Redux TypeScript application. It seems that after making some changes, one of the modules has stopped exporting its members. Here is the folder structure: src |---- components |---- contain ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

Having trouble locating module '@mdx-js/mdx' in Gatsby forest

Since the most recent update today, I've been encountering this error. There is no MDX being used in my project at all.. When running npm run develop, this issue arises. Does anyone have any insights on this? internal/modules/cjs/loader.js:979 thro ...

Azure Chatbot that logs conversations in Webchat whenever the user selects 'none of the above' option

Recently, I've delved into the world of web chat services and embarked on a journey to craft a chat bot using pure JavaScript code that can seamlessly integrate into any HTML file. Despite consulting Microsoft's documentation, I find myself in a ...

Ways to automatically update a page once the form response is received

After scouring various websites, I still haven't found a solution to my issue. What I need help with is how to refresh a page once a successful deletion message is received for a specific row. My admin2.php page displays information about the admin fr ...

Thick labels in Chart.js are shortened with three dots

Is there a way to show the entire label without it getting truncated with 3 dots? I have experimented with different options from https://www.chartjs.org/docs/master/axes/index, including padding, but so far I haven't been successful. The full date da ...

the reason behind the peculiar behavior of angularjs ng-include

I am attempting to utilize an ng-template to iterate through my args in order to create an indented menu content. Unfortunately, I have encountered issues with ng-include not working as expected. I have tried adding a quote but it still does not work. For ...

Ways to determine the types of props received by a function when the arguments vary for each scenario?

I have a specialized component that handles the majority of tasks for a specific operation. This component needs to invoke the onSubmit function received through props, depending on the type of the calling component. Below is an example code snippet show ...

Alter the truth value of an item contained within an array

Embarking on my JavaScript journey, so please bear with me as I'm just getting started :) I am working on a small app where the images on the left side are stored in an array. When a user clicks on one of them, I want to change its height and also tog ...

What is the best way to insert an <image> tag into the SVG DOM?

Currently, I am facing an issue with adding a background image to the generated SVG DOM in my web page. The user interacts by drawing an SVG doodle on top of a jpg image using Raphael. After the user is done with their drawing, I want to enable them to sa ...

How can the '!!user' syntax be utilized? What outcome does this code snippet produce?

I am looking to implement an angular route guard in my application. I came across this code snippet but I am confused about the line where user is mapped to !!user. Can someone explain the purpose of map(user => !!user) in this context? canActivate( ...

Utilize the power of jQuery accordion to organize and display your table

Is there a way to integrate jQuery UI Accordion with an HTML table so that columns can be collapsible? I have tried various methods but haven't been successful. Currently, this is what I have implemented: $(".col1, .col2").addClass("hidden"); $(".s ...

The integration of Vue JS is not displaying properly in an Electron application

My electron app is loading Vue JS 2 from my local machine, but when I attach my el to an element, it completely empties the element and replaces its contents with a Vue JS comment. What could be causing this issue? index.html <!DOCTYPE html> <htm ...

Is there a way to determine in FireBug the specific JavaScript code being received from the server following an Ajax request?

Within my HTML code, I am transmitting a dollar amount to the server in order to convert its currency within the application. Is there a way for me to use FireBug to track and view the JavaScript that is being received from the server following this Ajax ...

Firefox seems to handle webpages smoothly, whereas IE struggles to display them properly

Check out the code snippet below: self.xmlHttpReq = new XMLHttpRequest(); self.xmlHttpReq.onreadystatechange = function() { if(self.xmlHttpReq.readyState == 4 && self.xmlHttpReq.status == 200) { xmlDoc = self.xmlHttpReq.response ...