JavaScript is unable to identify the variable containing parsed JSON

I have been working on coding some gauges for the index page of the R/Shiny dashboards used by our company. The layout consists of several styled divs that link to different R apps.

Recently, our executives have shown interest in having fuel-gauge style graphs at the top of the page to represent $income and $goals for each division throughout the month.

To create the Gauges, I opted to utilize the JustGage plugin from JustGage. With a simple script provided by my supervisor to extract data from csv files and convert it into JSON documents on the server, we were able to generate a JSON file with just 6 lines.

Using an AJAX XMLHttpRequest seemed to work well initially. However, when attempting to store the parsed data into a variable and reference it within my Gauge parameters, I encountered the following error:

(index):182 Uncaught ReferenceError: feeData is not defined at (index):182 (anonymous) @ (index):182

This error occurs specifically on the first instance where the variable holding the JSON data is referenced.

Any assistance or guidance on this issue would be greatly appreciated!

< script >
  var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  var feeData = JSON.parse(this.responseText);
  if (this.readyState == 4 && this.status == 200) {
    var feeData = JSON.parse(this.responseText);
  }
};
xhttp.open("GET", "test.json", true);
xhttp.send();
var g = new JustGage({
  titleFontColor: "black",
  labelFontColor: "black",
  id: "DEF",
  value: feeData.DEFCurrent,
  pointer: true,
  min: 0,
  max: feeData.DEFGoal,
  title: "DEF"
});
var g = new JustGage({
  titleFontColor: "black",
  labelFontColor: "black",
  id: "EBO",
  value: feeData.EBOCurrent,
  pointer: true,
  min: 0,
  max: feeData.EBOGoal,
  title: "EBO"
});
var g = new JustGage({
  titleFontColor: "black",
  labelFontColor: "black",
  id: "Company",
  value: (feeData.EBOCurrent + feeData.DEFCurrent),
  pointer: true,
  min: 0,
  max: (feeData.EBOGoal + feeData.DEFGoal),
  title: "Company"
});
var g = new JustGage({
  titleFontColor: "black",
  labelFontColor: "black",
  id: "Legal",
  value: feeData.LegalCurrent,
  pointer: true,
  min: 0,
  max: feeData.LegalGoal,
  title: "Legal"
}); 
</script>

Below is the contents of the JSON file:

{"EBOGoal":1000,"EBOCurrent":900,"DEFGoal":2000,"DEFCurrent":1500,"LegalGoal":500,"LegalCurrent":450}

It's worth noting that the Gauges themselves function correctly when placeholder numerical values are substituted for the MAX and VALUE parameters in the JavaScript code for the Gauges.

Answer №1

Your variable declaration issue and timing problem need attention. Simply moving the variable out of the onreadystatechange function scope won't solve the issue because of the asynchronous data population. To address this, consider initializing your JustGage in a separate function and calling it only when the feeData is ready:

xhttp.onreadystatechange = function() {
  var feeData = JSON.parse(this.responseText);
  if (this.readyState == 4 && this.status == 200) {
    // call the initialization function with the data
    setupJustGage(JSON.parse(this.responseText));
  }
};

function setupJustGage(feeData) {
    ...
    var g = new JustGage({
      titleFontColor: "black",
      labelFontColor: "black",
      id: "DEF",
      value: feeData.DEFCurrent,
      pointer: true,
      min: 0,
      max: feeData.DEFGoal,
      title: "DEF"
    });
    var g = new JustGage({
      titleFontColor: "black",
      labelFontColor: "black",
      id: "EBO",
      value: feeData.EBOCurrent,
      pointer: true,
      min: 0,
      max: feeData.EBOGoal,
      title: "EBO"
    });
    ...
}

An alternative approach could be to encapsulate your XHR request in a function that returns a Promise, allowing you to handle the rest of the setup code in the then block:

function getData() {
    return new Promise(function(resolve) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          var feeData = JSON.parse(this.responseText);
          if (this.readyState == 4 && this.status == 200) {
            resolve(JSON.parse(this.responseText));
          }
        };
        xhttp.open("GET", "test.json", true);
        xhttp.send();
    })
}

getData().then(function(feeData) {
   var g = ...
})

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

Finding Table Changes in PHP with Drupal DatabaseDiscovering alterations in database tables using PHP and Drupal

Present scenario: The webpage currently uses AJAX/JQUERY to refresh its content every 17 seconds. Each time this occurs, the server fetches data from two tables in the database, one of which is quite large (450MiB in size, 11 columns) and processes the inf ...

How can you verify the value of a disabled HTML input element in TestCafe using Typescript?

TestCafe Typescript - how to verify the value of a disabled HTML input element? Despite being disabled for user interaction, I want to ensure that this element still holds the anticipated value. example public async checksomething(text: string) { co ...

Photoshop script for verifying layer names

I am currently working on a script to verify my images. Here are the criteria I need to validate: Determine the number of layers and pathItems in the document - relatively straightforward. Identifying the names of 3 specific layers: I have hit a roadblock ...

Prevent the execution of a Javascript function if it is already in progress

I've developed a function that retrieves records from a third party, and this function runs every 10 seconds. However, as I debug through Firefox, I notice a long queue of ajax requests. I'm contemplating including a statement that can signal to ...

Leveraging Isotope alongside imagesLoaded for dynamically loaded Ajax content

Using Isotope to create a masonry grid, I have incorporated a load more button that utilizes AJAX to fetch additional items when clicked. Within the AJAX success function, I generate the necessary HTML for the grid item in the following manner: htm = &a ...

What is the method for activating a hook after a state change in a functional component?

I'm currently working on a custom pagination hook that interacts with an API to fetch data similar to React Query. The concept is straightforward. I aim to invoke this hook whenever a specific state (referred to as cursor) undergoes a change. Below i ...

Tips for integrating Series data into Highcharts using MVC

Looking at this JFiddle demonstration of Highcharts http://jsfiddle.net/yxz80f4u/9/ We can observe the data being inserted as [Date.UTC(YYYY,MM,DD,HH,MM,SS), Y-data-point] data: [ [Date.UTC(1970, 7, 5,1,1,1), 2.22], [Date.UTC(1 ...

Node.js - Implementing URL Validation for User Input

I've been utilizing the node module 'request' to develop a job queue for retrieving HTML data from a URL entered by a user. Here's the current state of my code: var jobQueue = []; function processNextJob() { if (jobQueue.length &l ...

absence of data returned in Ajax call for a REST endpoint

Currently, I am testing a straightforward REST service that was created using Java. The server-side code includes: import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import ...

Cleaning PHP sessions upon page unload is a common task that many developers need to tackle

Is it possible to clear a session variable by calling the server side using AJAX or jQuery? I currently have a Facebook application that relies on PHP session variables for its behavior. I am looking for a way to clear these session variables when the use ...

iPad problem resolved: Disable click hover and double-click issue

I'm experiencing a problem with my web application specifically on Safari for iPad. I have to click twice in order to actually perform the click on the <a> tag. The first click triggers a hover effect, similar to when you hover with a mouse on d ...

Error while parsing Json - Start byte 0xa0 is not valid UTF-8 notation

I am facing a problem with sending Json data to the server. It seems like there are some bad characters at the beginning of the UTF-8 format that are causing issues. To fix this, I tried using CharDecoder to replace all the malformed utf-8 characters. Her ...

Automatically send a form with Ajax when the page is loaded

I have a form that needs to be automatically submitted when the page loads. Here is my current jQuery code: <script> // wait for the DOM to be loaded $(document).ready(function() { document.getElementById('form1').submit( ...

Assistance needed for adjusting margins and padding within the inner content box

I'm currently in the process of designing a new website layout using CSS, but I've encountered some challenges along the way. My main goal is to ensure that all elements stay within the boundaries of the browser window, with the scroll bar appear ...

Manipulating cursor position in React's contentEditable

I created a simple component class ContentEditable extends React.Component { constructor(props) { super(props); this.handleInput = this.handleInput.bind(this); } handleInput(event) { let html = event.target.innerHTML; if (this.props. ...

Decoding JSON data from a URL

I am attempting to dynamically generate image views from a JSON URL. Utilizing a for-loop, I am able to extract the URL and store it as a string. However, I encountered an issue when trying to access this variable outside of the loop. To resolve this, I ex ...

Save data to a JSON file within a Meteor application

I've been experimenting with running a small web scraper on Meteor using x-ray. My goal is to extract data and output it to a JSON file. While this setup works fine with node and express, I've run into issues when trying to get it working with Me ...

Color of the background in an Ionic tab

https://i.sstatic.net/lyhMu.jpg Hello, I am currently working on developing a mobile app using Ionic. I have utilized the Ionic tabs template, but I am facing an issue with the tab's background color remaining white at the bottom of the screen. Altho ...

Display the Meteor Simple Schema for Entities

I've created a Meteor application and set up some database collections with SimpleSchema from https://github.com/aldeed/simple-schema-js. Cards = new Mongo.Collection('cards'); Cards.attachSchema(new SimpleSchema({ title: { type: Str ...

Is the Angular-fullstack generator production application experiencing issues with serving socket.io correctly?

Having a bit of trouble with two angular-fullstack apps deployed on AWS using the same setup and configuration. It appears that socket.io-client/socket.io.js is not being properly served on one of them, despite both apps having identical settings. There ...