Array scripts are removed once data has been extracted from the CSV file

Having trouble reading a CSV file using file reader in Javascript. I wrote a script that declares arrays and updates them as the file is read. However, once the reading is complete, all data from the arrays gets wiped out. I'm quite new to JS and can't figure out why this is happening. I suspect it has something to do with the scope of the arrays, even though I declared them as global variables. Any help would be appreciated!

var paper = [];
var recyclables = [];
var compost = [];
var landfill = [];

function readCsvFileData(type, index) {
    readCsv();
    if(type == "paper"){
        console.log("requested type - " + paper.length);
        console.log("wrong answer here -- 0 ");
        return paper[index];
    }
}

function readCsv() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if(this.readyState == 4 && this.status == 200){
            console.log(this.responseText);
            var line = this.responseText.split("\n");
            for(let row = 1; row < line.length; row++){
                let rowData = line[row].split(',');
                for(let col = 1; col < rowData.length; col++){
                    if(col == 1 && paper.length<12){
                        paper.push(rowData[col]);
                    }
                    if(col == 2 && recyclables.length<12){
                        recyclables.push(rowData[col]);
                    }
                    if(col == 3 && compost.length<12){
                        compost.push(rowData[col]);
                    }
                    if(col == 4 && landfill.length<12){
                        landfill.push(rowData[col]);
                    }
                    if(paper.length==12 && recyclables.length==12 && compost.length==12 && landfill.length==12){
                        console.log("retruning "+landfill.length);
                        console.log("correct answer here -- 12");
                        return true;
                    }
                }
            }
        }
    }
    xhttp.open('GET', "Data.csv", true);
    xhttp.send();
}

Answer №1

As mentioned by Jay Buckman in the comments, you are using asynchronous processing in your code. This means that the function readCsv returns immediately without waiting for the send() method to finish. As a result, the readCsvFileData function proceeds to the if condition before the arrays are populated. To address this issue, it is necessary to incorporate an event listener or callback method. You can try implementing the following solution:

var paper = [];
var recyclables = [];
var compost = [];
var landfill = [];

function readCsvFileData(type, index) {
    readCsv(function() {
        if(type == "paper"){
            console.log("requested type - " + paper.length);
            console.log("incorrect answer displayed -- 0 ");
            return paper[index];
        }
    });
}


function readCsv(onCompleteCallback) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if(this.readyState == 4 && this.status == 200){
            // ... your standard implementation

            // execute the complete callback function provided
            onCompleteCallback();
        }
    }

    xhttp.open('GET', "Data.csv", true);
    xhttp.send();
}

Additional information on this topic can be found here. It is generally recommended to set the async argument when making requests. Failing to do so may cause synchronous execution, potentially blocking the main thread (user's browser) until the operation finishes, which is not desirable.

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

Preventing runtime error in Next.js API routes by handling axios exceptions

I am currently working on creating an API route in Next.js that sends a request to my backend and saves the token in the cookies. However, I am facing an issue where 4xx responses are causing an Unhandled runtime error. Despite everything working correctly ...

AngularJS: Understanding the difference between ng-show and using display:none

I recently encountered a scenario where I needed to hide an HTML element by default using CSS. Here's how I did it: HTML: <div class="box"> </div> CSS: .box { display: none; } However, I wanted to be able to show and hide the elem ...

In Node JS, the variable ID is unable to be accessed outside of the Mongoose

When working with a Mongoose query, I encountered an error where I am trying to assign two different values to the same variable based on the query result. However, I keep getting this error: events.js:187 throw er; // Unhandled 'error' ev ...

Use JavaScript and AJAX to easily assign multiple variables with unique IDs to an array with just one click

This function is no longer supported Original query : I would greatly appreciate any assistance and guidance. I am attempting to create a function that moves selected products from the Cart to another table so I can reorder them according to customer de ...

Is there a way to create a JavaScript function that relies on a successful form submission?

After attempting to modify a post on Stack Overflow, I am facing issues with my JavaScript code. As a beginner, it's possible that I overlooked something in the code causing it not to work as expected. The project I'm working on involves creatin ...

Harmonizing Express (Passport) with AngularJS Routing

I have been working on developing a MEAN-stack application and I have reached the point of setting up user authentication. Following this tutorial: After implementing it into my project, I noticed that it works partially. The issue is that I can only acce ...

Check if the data-indices of several div elements are in sequential order using a jQuery function

Is there a way to implement a function in jQuery-ui that checks the order of div elements with data-index when a submit button is pressed? I have set up a sortable feature using jQuery-ui, allowing users to rearrange the order of the divs. Here is an exam ...

Best method for distributing components across nextjs zones?

Scenario: I am currently working on a project using Next.js and taking advantage of its multi zones feature. This feature allows us to run multiple independent NextJS applications as a unified app, managed by different teams. The Issue: One challenge I fa ...

Challenges faced when retrieving data from a web API using JavaScript with REACT

Having trouble retrieving data from a Web API in React. The API URL is and I've stored it in a state called pokeData. When I do a console.log(pokeData), everything works fine. Likewise, there are no issues with console.log(pokeData.types). However, ...

What is the best way to refresh my useEffect hook when a State change occurs in another component's file in ReactJS?

Seeking to execute an API call within useEffect() and aiming for the useEffect() function to trigger every time new data is appended to the backend. To achieve this, a custom button (AddUserButton.js) has been created to facilitate adding a new user to the ...

Updating objects in Angular 8 while excluding the current index: a guide

this.DynamicData = { "items": [ { "item": "example", "description": "example" }, { "item": "aa", "description": "bb" }, ...

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

Navigate to a fresh HTML page upon form submission

I'm completely new to the world of web apps and JavaScript, and I'm facing an issue where my form submission doesn't redirect me to a thank you page. Instead, it just leads to a blank page every time. I've tried researching solutions on ...

Retrieve files from Amazon S3 using JavaScript

I'm currently working with a javascript file that's intended to download a text file from one of my S3 buckets. However, after running this file using "node file.js", nothing happens and there's no output. Is there something I'm missing ...

Tips for utilizing browser cache in AJAX requests to prevent loading the refreshed JSON file

It may seem like a strange question, but I'm experiencing an issue with an AJAX call to a JSON file. Both the request and response headers do not indicate to not use cache, and in the browser settings, the Disable cache option is not checked. What mor ...

PHP Ajax Image Uploading and Storage

Is there a way to effortlessly upload an image and save it in the uploads folder without any page refresh? Not only that, but can we also have the uploaded image displayed on the screen within a designated div section? Unfortunately, I seem to encounter a ...

Unable to set the cookie when using the fetch API

My node.js server is listening on port 3001. WITHIN THE REACT FILE On the login page component. fetch('http://localhost:3001/api/login',{ method:'POST', headers: { Accept: 'application/json', ...

Perform multiple function invocations on a single variable using JavaScript

Is there a way to execute multiple functions on a single object in JavaScript? Maybe something like this: element .setHtml('test'), .setColor('green'); Instead of: element.setHtml('test'); element.setColor('gre ...

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

Having trouble sending HTTP requests in Angular 6

I am currently facing an issue in my Angular application while trying to send an HTTP POST request to a Spring RESTful API. Despite my attempts, I have not been able to succeed and I do not see any error response in the browser console. Below is a snippet ...