What is the best way to incorporate a JSON file into a JavaScript class?

I attempted to load a JSON file within a JavaScript class, but encountered an issue where the loaded data was only accessible inside a specific function.

 class CreatePage {
     constructor() {
        var request = new XMLHttpRequest();
        request.open('GET', 'data.json');
        request.responseType = 'json';
        request.send();
        request.onload = function() {
            this.data = request.response;
            alert(this.data[1].Name); // This works
        }       
    }
    
    test(name) {
        document.getElementById(name).innerHTML = this.data[1].Name;
    }
}

const page = new CreatePage();
page.test("xyz"); // TypeError: this.data is undefined

Is there a way to store the loaded data as a class property?

EDIT: I appreciate the responses received so far. Despite trying solutions like `self=this`, `bind(this)`, and the arrow operator, I am still encountering the same TypeReference error.

Answer №1

Simply swap out your callback function with an arrow function. When you make this change:

this.daten=request.response

this may not be what you assume it is ;) By using an arrow function, the value of this remains unchanged and will behave as expected.

class MakePage {
     constructor() {
        var request=new XMLHttpRequest();
        request.open('GET','daten.json');
        request.responseType='json';
        request.send();
        request.onload = () => {
            this.daten=request.response;
            alert(this.daten[1].Name); // this works
        }       
    }
    test(name) {
        document.getElementById(name).innerHTML=this.daten[1].Name;
    }
}

Alternatively, you can utilize bind.

    request.onload=function() {
        this.daten=request.response;
        alert(this.daten[1].Name); // this works
    }       
    request.onload = request.onload.bind(this);

Remember to refer to the documentation to gain a thorough understanding of how it operates: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Answer №2

Consider swapping out the following code snippet:

request.onload=function() {
    this.data=request.response;
    alert(this.data[1].Name); // this works
} 

with an arrow function like so:

request.onload=()=> {
    this.data=request.response;
    alert(this.data[1].Name); // this works
} 

Answer №3

To enhance the callback function, make sure to include a reference like this:

 class GenerateContent {
     constructor() {
        var req=new XMLHttpRequest();
        req.open('GET','data.json');
        req.responseType='json';
        req.send();
        self=this;
        req.onload=function() {
            self.data=req.response;
            alert(self.data[1].Title); // see how it works
        }       
    }
    displayInfo(title) {
        document.getElementById(title).innerHTML=this.data[1].Name;
    }
 }

Answer №4

The this keyword within the context of the request.onload=function() does not point to the correct scope.

To address this issue, you can either utilize an arrow function such as request.onload = () => {} (which is the recommended approach), or store a reference to the outer scope by assigning const self = this at some point within the constructor.

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

Is it possible in HTML to detect *any* changes made to an input, not just those made by the keyboard?

Let's consider a scenario where we have an input element like this: <input id="myInput" type="text" /> The question now arises, how can we detect when the value of this input is changed programmatically (such as through $("#myInput").val("new ...

Using jQuery to load HTML response into entire page

When working with my ajax code, I receive a html response. Is there a way to entirely replace the current page with this html response? So far, I have only come across window.location.href, which simply redirects to the url response. Here is a snippet of ...

Arranging elements on a webpage using Javascript

Creating a Dynamic Div Layout with JavaScript I have successfully implemented functionality wherein clicking on + opens a div and clicking on - closes it. However, I am now faced with the challenge of handling multiple divs at runtime. How can this be ach ...

Where can content-tag and main-tag be found in vue-virtual-scroller?

I've been trying to wrap my head around the vue virtual scroller. I couldn't help but notice in the demo that it utilizes a few HTML attributes... <virtual-scroller v-if="scopedSlots" class="scroller" :item-height="itemHeight" :items="items" ...

When working on a REST APIs project with ReactJS fetch and NodeJS, I am encountering difficulties in reading authorization headers on the server side

I'm having issues retrieving headers on the server side using ReactJS fetch to call an API on the front end. In my old project, this functionality was working perfectly fine. I'm puzzled as to why it's not working now, especially since I hav ...

What method can I use in webpage coding to achieve this special highlight effect, and what is the official term for it?

Need help figuring out how to make an icon change from blue to white when selected. I've searched through Bootstrap, CSS, and HTML, but haven't found the solution yet. Any suggestions would be appreciated! https://i.stack.imgur.com/RK1PD.png ...

Is async programming synonymous with multi-threading?

Discussing a JavaScript code that utilizes the setInterval function every 2 seconds. There is also an animation event for some control triggered by the onblur event. If the onblur event occurs (along with the animation), there is a possibility of encount ...

What is the best way to implement a sub-menu using jQuery?

After successfully implementing a hover effect on my menu item using CSS, I am now struggling to make the sub-menu appear below the menu item upon hovering. Despite my efforts to search for jQuery solutions online, I have not been successful. Are there a ...

Problem arising from animation not commencing at expected starting point

Creating a feature on an app that involves breathing exercises using CSS animations. The challenge I'm facing is ensuring the words "exhale" and "inhale" appear synchronously with the animation of a circle shrinking and enlarging. However, the animati ...

Display refined outcomes on the search results page

In my app, the main feature is a search box on the homepage. Users can input their search queries and upon submission, they are redirected to a result page displaying the relevant results along with filtering options. The filtering functionality allows use ...

The clear function in the template slot of Vue multiselect is not functioning properly

I decided to incorporate the asynchronous select feature found in the documentation for my project. This feature allows me to easily remove a selected value by clicking on 'X'. Below is a snippet of the general component that I use across variou ...

Restricting variable values in Node.js

As I work in an IDE, there is a feature that helps me with autocomplete when typing code. For example, if I type: x = 5 s = typeof(x) if (s === ) //Cursor selection after === (before i finished the statement) The IDE provides me with a list of possible ...

Is there a way to incorporate multer middleware into my express controller without using the router?

This is the structure I typically follow when writing controllers and routes using Express controller exports.postBlog = async (req, res, next) => {...} routes router.route("/post").post(onlyAdmin, postBlog); *onlyAdmin serves as a middlewa ...

Emphasize the Jqgrid row when clicked on, but do not check the multiselect checkbox

Is there a method in jQgrid to highlight a row when clicked without selecting the multiselect checkbox? I attempted using Multiboxonly = true as suggested by Oleg on Your assistance would be greatly appreciated, as this issue is currently hindering progr ...

Using JQuery to extract information from a JSON file

Here is the code I am working on, where I pass input username and password values. The function I have written checks if the input matches the data in a JSON file. If there is a match, an alert saying "login correct" will be displayed, otherwise it will di ...

Looping through elements using .each in jQuery and accessing their values in the following iteration

Here is the code snippet I've been working on: var index=0; var load=0; $("td.load_ads").each(function(){ var loading=$(this); $.post('/self_coded_helpers/jpost_get_ads.php',{index:index,type:'fetch_id' ...

Ways to retrieve nested data from an object

I have added an object with categories in a database. It displays the price and date of addition. How can I output the date to the console? Currently, in the console, it shows: [ [ { cost: '50$', date: [Object] } ] ]. I need to extract the inform ...

What could be causing the issue with export default not functioning as expected in this straightforward code?

Whenever I try using export default in the index.js module, it gives me an error message saying: "export 'appReducers' (imported as 'appReducers') was not found in './reducers/index' (possible exports: default). However, when ...

Top Method for Reloading Element-Specific JavaScript When Replacing Elements

Is there a better way to re-initialize JavaScript without needing a page refresh? I'm currently struggling with appending an MDBootstrap <select> tag, which involves more than just adding a child element. Instead, I have to remove the element an ...

Creating a personalized Autocomplete feature using React Material-UI with the help of the renderInput method

I'm currently using a React Material UI Autocomplete component, similar to the one in the official documentation. For example, let's consider a list of countries: import * as React from 'react'; import Box from '@mui/material/Box& ...