Passing data from an ajax request to multiple functions in Javascript: Best practices

Currently, I have a function named impactData which is making an ajax call to retrieve data from a CSV file that I created. Upon success, the retrieved data is passed to my generateImpactData function, which converts the CSV file into an array of objects. Finally, the array called impactArr is passed to the drawBarGraph() function.

While this setup works well, I am now looking to streamline my code by creating a new function called appendImpactData, which will append some of the data to cards on my website unrelated to the bar graph.

When attempting to pass the impactArr to the appendImpactData function, I encounter a return value of undefined, even though the drawBarGraph function has no problem accessing the data. My goal is to ensure that both functions have access to the impactArr data after the generateImpactData function.

Below is the relevant code:

function impactData() {
    $.ajax({
        type: "GET",
        url: data,
        async: true,
        success: function (data) {
            appendImpactData(drawBarGraph(generateImpactData(data)))  // trying to pass data to all 3
        },
        error: function (e) {
            // handle exception
            console.log("Error occurred while reading resource file: ", e);
        }
    });
}

The first function passes data from the successful ajax call:

function generateImpactData(data) {

let dataList = [];
    let csvObjects = $.csv.toObjects(data);

for (var i = 0; i < csvObjects.length; i++) {
        sector = csvObjects[i]["Sector"];
        impact = csvObjects[i]["Impact"];
        date = csvObjects[i]["Date"];

var arrDataListItems = [
            sector,
            impact,
            date,
        ];

        dataList.push(arrDataListItems);

    }


const urlStr = window.location.pathname;
const impactArr = []
const recoverArr = []

if (urlStr.includes('/impact/') {
 impactArr.push(dataList[0][2], dataList[0][3], dataList[0][4])
} else if (urlStr.includes('/recovery/') {
recoverArr.push(dataList[2][2], dataList[2][3], dataList[2][4])
}

return { impactArr: impactArr 
         recoverArr: recoverArr
};

}

The second function, where impactArr data is visible:

function drawBarGraph(impactArr) {

console.log(impactArr) // data is returning fine

}

The third function, where impactArr returns undefined:

function appendImpactData(impactArr) {

console.log(impactArr) // returning undefined, I am attempting to access the data here also

}

Answer №1

You currently have the following setup:

function drawBarGraph(impactArr) {
  console.log(impactArr) // data is returning fine
} // returns undefined
function appendImpactData(impactArr) {
  console.log(impactArr) // returning undefined, I am attempting to access the data here also
} // returns undefined

And you are invoking them like this:

appendImpactData(
  drawBarGraph(
    generateImpactData(data)
  )
)

This means that each function is being called with the returned value of the previous one.

You have a couple of options to consider:

1) You can modify your functions to return the data:

function generateImpactData(impactArr) {
  // Do something
  return impactArr;
}
function drawBarGraph(impactArr) {
  // Do something
  return impactArr;
}
function appendImpactData(impactArr) {
  // Do something
  return impactArr;
}

2) Alternatively, if there is no inherent relationship between them, you can call them independently:

function impactData() {
    $.ajax({
        type: "GET",
        url: data,
        async: true,
        success: function (data) {
            const impactArr = generateImpactData(data);
            appendImpactData(impactArr);
            drawBarGraph(impactArr);
        },
        error: function (e) {
            // Handle errors
            console.log("An error occurred while reading the resource file: ", e);
        }
    });
}

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

Transform the response before sending it with the Hapi.js Proxy

Currently, I am in the process of testing out Hapi.js for a new project that is part of my current workload. My main objective is to initiate a request on my Hapi server which will then trigger another request on an external server using the Hapi proxy fun ...

AngularJS - A guide on adding a new property to every object within an array

I'm looking to update each item in an array by pushing a scope variable into it. This is my current code: $scope.ProcessExcel = function (data) { //Read the Excel File data. var workbook = XLSX.read(data, { type: 'bin ...

Determine if two arrays have the same object values

I have a situation where I am working with two arrays of objects. arr1 = [{ name: "John" }, { name: "Frank" }]; arr2 = [ { name: "John", age: 35 }, { name: "Frank", age: 22 }, { name: "Kate", age: 23 ...

Determining outcomes of forms added in real-time

Need assistance with dynamically creating tickets, calculating prices, and displaying results when additional tickets are added. Currently facing an issue where price data is not being calculated when a new ticket is added. Any help would be greatly apprec ...

Update the HTML weather icon with data from JSON

I have a collection of weather icons stored on my computer. How can I customize the default weather icons with my own set of icons? In the JSON file, there is a variable like this: "icon":"partlycloudy" <html> <head> <script src="http://c ...

What methods are used to maintain the state of the express req.session object?

My journey into learning Node and Express is just beginning, and I am currently trying to comprehend the flow of code with Express. Imagine you have code like this in a session.js file: app.post('/session', notLoggedIn, function(req, res) { ...

I am facing an issue with the Options functionality in Materialize, and the remove method does not seem to work when I am using the

Having a little trouble appending options in a materialize select for my project. Can someone take a look at my code snippet below and provide some guidance on what changes I should make? Thanks! $(document).ready(function() { $(".condition").click(fu ...

Create a dynamic animation page using Node.js, then seamlessly redirect users to the homepage for a smooth user

Good day everyone! I've decided to change things up with my latest query. I'm currently working on adding a loading page animation that will show for 3 seconds when visiting the '/' route, and then automatically redirect to the home pag ...

Issues with data retrieval from Server using .NET Core and Ajax, despite successful retrieval on local environment

My Ajax Codes working fine locally, but I'm not getting any data on my Ubuntu server. I suspect the issue lies with the date settings. The code seems to work when there is no date involved. I am unsure how to check and adjust the date settings on my ...

Rearrange Firebase data on the client side

Having trouble sorting data in Firebase for a web project. I tried using orderByChild to filter the data, but now I need to also order it by date. Here's what I've attempted: Tried using object.values with .sort, no luck Attempted to use lodas ...

Encountered a WebDriverException when attempting to capture a screenshot

While attempting to capture a screenshot from my Firefox browser, I encountered the following exception: org.openqa.selenium.WebDriverException: [Exception... "Data conversion failed because significant data would be lost" nsresult: "0x80460003 (NS_ERROR ...

How can the AJAX request be adjusted to ensure that the dependent drop-down is hidden when the page initially loads?

My current form includes a dependent drop-down feature. Right now, both the main drop-down and the dependent one are displayed when the page loads. If a "Work Area" without a "Station" is selected, then the station drop-down disappears. What I want to acc ...

Issue encountered when attempting to unzip a file of size 12 megabytes

I have been using a specific open source tool to unzip files, and it works well for zips ranging from 2-5 MB. However, I encountered an error when trying to unzip a zip file that was over 10 MB in size. Are there any more reliable open source options ava ...

What is the reason for Nightwatch running each .js file as a Child process? Could it be due to alterations in the configuration settings

Recently, I've been experiencing an issue when running Nightwatch.js where my console is spawning child processes for every .js file in each folder and subfolder. Multiple Chrome instances are opening along with them and even the module folders with r ...

Trigger an endless loop upon window.onload event

Every now and then, when a user opens the page, it starts flickering and resizing itself. After checking the log, it appears that the submit function is being called multiple times, but I can't reproduce this issue in my own environment. Is there som ...

How can we redirect using an OnClick event handler in React.js?

I've been doing a lot of reading and trying to understand how to redirect using withRouter in React. However, I came across some information stating that when onClick occurs, the page should be redirected to a specific link. Additionally, I learned th ...

What are the steps to resolve the error 'content-type missing boundary' and encountering the issue with getBoundary not being recognized as a function?

fetchCarouselData: async (params) => { let bodyFormData = new FormData(); for (let prop in params) { bodyFormData.append(prop, params[prop]); } return axios({ method: "post", url: `${baseURL}/fetchCarouselData`, data: b ...

displaying solely the bottom two rows while concealing the remainder

Looking for a Google Docs script that can automatically display only the last two rows in a spreadsheet. The goal is to have the new data added in a row and when ENTER is pressed, it will show only the latest two rows while hiding all others. I've st ...

Typescript is throwing an error when trying to use MUI-base componentType props within a custom component that is nested within another component

I need help customizing the InputUnstyled component from MUI-base. Everything works fine during runtime, but I am encountering a Typescript error when trying to access the maxLength attribute within componentProps for my custom input created with InputUnst ...

Ways to calculate the memory utilization of a JavaScript object

Suppose I want to compare the efficiency of storing bits of a static canvas/image with Alpha more or less than 0.5 using an "array of array of number" versus an "array of string," which would be better in terms of memory usage and speed? var c = $('m ...