Universal variable failing to receive global updates

My goal is to create a webpage that displays a family tree using JSON data. I am utilizing the uploadJSON() function to save the JSON data from a file into the global variable tree. Everything seems to be working fine until I try to access tree in another function. When I use console.log(tree); inside addToDropDown(), it displays as undefined in the console. I attempted setting tree to a default value of "Testing" upon initialization, but it remains unchanged when I call uploadJSON().

let tree;
let dropDown;

window.onload = function() {
    // Upload JSON File
    document.getElementById('upload-button').onclick = function() { uploadJSON(); };
    
    // Get Dropdown
    dropDown = document.getElementById('family-member-select');
}

function uploadJSON() {
    let files = document.getElementById('upload-file').files;
    if (files.length <= 0) {
        return false;
    }

    let fr = new FileReader();

    fr.onload = function(e) {
        console.log(e);
        let result = JSON.parse(e.target.result);
        tree = result;
        console.log(tree); // This correctly outputs the tree object from the JSON file
    }

    fr.readAsText(files.item(0));

    addToDropdown();
}

function addToDropdown() {
    // Populate dropdown list with family members

    console.log(tree);
}

Answer №1

fr.onload is used to set an event listener, triggering the execution of the addToDropdown() function. However, there is a possibility that when addToDropdown() is called, fr.onload has not been triggered yet. To ensure proper functionality, it would be ideal to invoke the addToDropdown() function within the fr.onload event itself. This way, the function will only be executed once the event is fired.

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

Methods for delivering static resources on multiple routes in Express JS

Is there a way to effectively serve static resources for all routes in Express JS? I attempted to serve files with static resources using the following code snippet: app.use(Express.static(`${this.PATH}`)); app.use(Cors()); app.use(Express.json()); app.g ...

The active class in the Bootstrap carousel is not updating when trying to change

I am struggling to make the Twitter Bootstrap carousel function properly. Although the slides automatically change after the default timeout, the indicators do not switch the active class, resulting in my carousel failing to transition between slides. Ini ...

How can I identify when a node/express ajax request is received?

I have set up a node/express server that sends the ajax-start.html file. Within this file, there is a script that enables ajax requests to be made to the server. Everything functions correctly in this setup. However, I am looking to enhance this process by ...

Most effective method for sending information from an HTTP server to a browser client

What is the most effective method for transferring data from the server side to the client when the client is a web browser? The server side is developed in Java, while the client side uses HTML, JavaScript, and AJAX. The communication protocol being uti ...

Execute a JavaScript function when an element loaded via Ajax in a Spring MVC framework triggers the onChange event

I currently have a dropdown list with two values and I am looking to enable or disable four components based on the user's selection. If the user picks the first value, the components should be enabled, otherwise they should be disabled. On the main ...

Autoselecting Dropdown Field on Wordpress Contact Form 7 Depending on Referral URL

I have been referencing the following two answers: Wordpress Contact Form 7 dynamically select dropdown field based on url Auto-select fields in Contact form 7 based on referral link The code snippet below is currently inserted in the CSS block on the / ...

The state remains unchanged when useState is invoked

I am currently designing a unique restaurant website template. As part of the project, I have implemented a modal box with two arrow buttons to navigate between pages. The issue I am facing is that the value of the pageNumber variable, tracked using useSta ...

Using PHP to reset variables for dynamic display in JavaScript

I've been working on retrieving values from a database and storing them in JavaScript variables. While I was successful in accomplishing this task, I encountered an issue when the values in the database are updated - the values of the variables remain ...

Defining a PHP function with empty parameters

What is the most effective way to organize a function with parameters that may be null? For example: function generateDate($day, $time = null, $override) { Do something with the variables } # generateDate('12', '', 'yes') ...

Updating a Rails partial using JSON response from an AJAX post request

I recently implemented an AJAX post request in my backend Rails application to upload a file. Upon successful posting, the response contains a JSON list of files. Now, I face the challenge of reloading the file list on my 'detalhes.html.erb' vie ...

Ways to add elements to a non-existent index in an array

I am facing an issue while attempting to form sets of objects in an array and generating a new set if the item is not already present. The structure of the data looks something like this: [ { "order": orderData, "items": itemData }, { "or ...

How can I achieve a "tab selector" effect with "input" elements on a website?

I am attempting to add "tab-highlights" similar to the ones shown above the form in the screenshot to my "input" elements. This will help users know which field they are currently focused on or have clicked. I have tried using "focus" and "::selection" to ...

Unwanted additional data inserted while sending JSON information through cURL

I'm working on building an API using cURL and JSON. In my initial PHP file, I am sending data as JSON like this: public function index() { $url = 'http://172.24.130.50/testbiz/server/login'; $field_string = "{“Request”: “Logi ...

Calculate the sum of values in a JSON array response

I recently received a JSON string as part of an API response, and it has the following structure: { "legend_size": 1, "data": { "series": [ "2013-05-01", "2013-05-02" ], "values": { "Sign Up": { "2013-05-05": 10, ...

The variable "vue" is not properly defined within the instance, yet it is being called

I'm currently working on a Vue app and encountering an issue. The onScroll function is working correctly, but when I click the button component to trigger the sayHello function, I receive an error message. The error states: "Property or method &apo ...

Guide to setting the order of rendering in React applications

I am currently working with a .tsx file that renders two components: export default observer(function MyModule(props: MyModuleProps) { .... return ( <div> <TopPart></TopPart> <LowerPart>< ...

Displaying information from a JSON file in PHP using a foreach loop

So I have these two JSON files, one with questions and the other with user answers. My goal is to display the questions from one file and the corresponding answers from the other file inside a div. I attempted using nested foreach loops, which did work bu ...

Trouble with Nextjs Version 11: Redirects resulting in double slashes in URLs

I am encountering an issue in my code where a relative path is causing a double slash in the URL. The scenario is as follows: //Nextjs config being imported to the react component const domain = 'https://testsite.com' let testUrl = `${domain}/i ...

Navigating the From and To routes in Nuxt/Vue: A comprehensive guide

I am currently working on a Nuxt/Vue project. While inspecting in Dev Tools, I came across a From and To property. How can I access these properties within the Nuxt application? I have attempted to use this.$nuxt.$route, this.$nuxt.$router, and this.$rou ...

The number counter feature in jQuery does not support the use of commas

I'm currently working on a counter that goes from 0 to a specific value, but I'm running into some issues with rendering numbers when they have commas. I've tried using toLocaleString as a potential solution, but I haven't been able to ...