Storing the response from a JSON file after using XMLHttpRequest in JavaScript and accessing it as a global variable for use throughout the program

Having an issue with storing JSON data retrieved using XMLHttpRequest into a global variable within my JavaScript file. Despite setting up the code to store the response in a global variable, it doesn't seem to be working as expected. Would appreciate any insights on why this might be happening and how I can achieve successful storage.

Below is the code snippet:

var xmlhttp = new XMLHttpRequest();
var url = './output.json';
var myArr;

xmlhttp.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
    let arr = JSON.parse(this.responseText);
    console.log(arr);
    myFunction(arr);
  }
};
xmlhttp.open('GET', url, true);
xmlhttp.send();

function myFunction(arr) {
  myArr = arr;
  console.log(myArr);
}

console.log(myArr);

The final console log output indicates 'undefined' instead of displaying the expected JSON array.

Hoping for a solution where the last console log accurately displays the JSON data as an array.

Answer №1

Here's a simple way to accomplish this task: just assign the api response directly to a global variable.

    let myData; // declare a global variable to hold the response

    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'data.json', true);
    xhr.onload = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        myData = JSON.parse(xhr.responseText); // store the response in the global variable
      }
    };
    xhr.send();

    // Now you can access the myData variable throughout your program
    console.log(myData);

Answer №2

XMLHttpRequest operates asynchronously.

If you use a console.log outside of this operation, it will run before the asynchronous part kicks in.

To efficiently handle myArr, stick to working within the myFunction.

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

Determine the instance's name as a string in JavaScript

Currently, I am utilizing Three.js in combination with javascript. Upon running the following line of code: console.log(this.scene.children[1]) I receive the following output in the console within Chrome: https://i.stack.imgur.com/6LBPR.png Is there a w ...

What is the best method for inserting a line break into a string?

Can you please explain how I can insert a line break into a string with JavaScript? I have tried using the <br/> tag, but it's not working. What is the correct way to achieve this? JavaScript var str="Click Here" +"<br>"+ "To Set" +"< ...

What could be causing the error in sending JSON data from JavaScript to Flask?

Check out this cool javascript code snippet I wrote: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $.ajax({ type: 'PO ...

Angular: What methods can I utilize to prevent my $http requests from causing UI blockage?

The following code snippet is from my controller: PartnersService.GetNonPartnerBanks().success(function (data) { vm.nonPartnerBanksList = data; }).error( function () { vm.nonPartnerBanksList = []; }); This code calls the service s ...

Triggering a JavaScript function when the mouse moves off an element

Recently, I created the following code snippet for marquee effect. The main functionality it is missing is triggering a function on mouse-over. <marquee class="smooth_m" behavior="scroll" direction="left" scrollamount="3"> <span style="float:le ...

The integration of socket.io with static file routing in node.js is encountering issues

I am currently developing a chat application and I have encountered an issue. When the static file routing is functioning correctly, the socket.io for the chat feature throws a "not found" error in the console. http://localhost/socket.io/?EIO=3&tran ...

Cannot transmit unprocessed json data through retrofit

I've been struggling to send raw JSON using Retrofit 2 but for some reason, it's not working. I've experimented with JsonObject and map, but nothing seems to be working at all. It's strange because the request works fine on Postman. Her ...

I'm interested in learning more about how to select or deselect all checkboxes

How can I uncheck the "all" checkbox when I uncheck another checkbox? $('#All').click(function () { var status = $(this).is(":checked"); if (status) { $.each($('input[name="checkbox"]'), function () { this. ...

``on click of the back button of the browser, automatically submit the form

I'm facing a specific issue that I need help with. I have created a form with a hidden value, and I want it to be submitted when the user clicks the browser's back button. Although I've managed to control the backspace key, I haven't be ...

Convert JSON strings with varying formats into objects of a uniform Java class

How can I deserialize JSON strings with different formats into instances of the same Java class using Jackson efficiently? Let's say I have information about users from various sources: Format 1: "user" : { "name" : "John", "age" : 21, ...

Sequencing asynchronous operations with node.js using sails.js

When setting up my Sails.js app, I have a series of tasks that need to be executed in order, with each task depending on the successful completion of the previous one. If any task encounters an error, the entire process should stop and prevent the app from ...

Guide on integrating next-images with rewrite in next.config.js

I'm currently facing a dilemma with my next.config.js file. I've successfully added a proxy to my requests using rewrite, but now I want to incorporate next-images to load svg files as well. However, I'm unsure of how to combine both functio ...

Unexpected behavior encountered when using the $http.post method

I've been working with a component that I utilized to submit data to the Rest API. The code snippet for the component is as follows: (function(angular) { 'use strict'; angular.module('ComponentRelease', ['ServiceR ...

Analyzing the audio frequency of a song from an mp3 file with the help of HTML5 web audio API

Currently, I am utilizing the capabilities of the HTML5 web audio API to detect when a song's average sound frequency drops below a specific threshold and create corresponding markers. Although I have successfully implemented this using AudioNodes, th ...

Regular expression for validating passwords will be disregarded

I crafted this javascript and html code to validate the username and password input. Strangely, the regular expression for the password is not being acknowledged. function checkDetails() { var uname = document.getElementById("uname").value; var pass ...

Heroku encounters an issue when attempting to launch the application using the command"npm start."

Every time I deploy my application to Heroku, the build process goes smoothly. However, as soon as it attempts to run the start script using npm start, it gets stuck and eventually crashes. I've tried various troubleshooting steps without success, and ...

The image tag fails to appear on the browser when the client attempts to access it

Greetings, I am new to web development. I am attempting to create a simple static website that only displays an image in the header tag of an HTML file. The server seems to be working correctly in sending responses to the client, but the problem lies in t ...

jQuery Counter Effect encountering isNaN error when trying to display a number retrieved from a get API object

I am looking to display the numerical data retrieved from an API using JSON. I want to incorporate a counter effect that displays "isNaN" if necessary. The API URL returns an object with the total number saved in data.data. Can anyone assist me with achi ...

What is the best way to create an array within an object during the parsing process

When working with a JSON object, I need to assign a value stored in the session against an ID. The JSON data is as follows: [ { "id": "a", "text": "a", "icon": true, "li_attr": { "id": "a" }, "a_attr": { "href": "#" ...

Optimal method in Ruby on Rails for sending model-specific attributes for grouping functions

I am currently working on implementing client-side list grouping functionality in my Rails application. The goal is to create a user list view where the user model can be grouped by different attributes such as email, name, title, etc. My plan is to have t ...