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

What steps can I take to troubleshoot the cause of my browser freezing when I try to navigate to a different webpage

Within this div, users can click on the following code: <div id="generate2_pos" onclick="damperdesign_payload();" class="button">Generate P-Spectra</div> Upon clicking, the damperdesign_payload() function is triggered, leading to a link to an ...

Passing parameters in a jQuery function through a button click

I am trying to figure out how to pass the @item.Id value as a parameter in the click function for a button. Here is the code snippet: <button id="buttonEdit" style="color:darkgreen" data-toggle="modal" data-target="#Ed ...

looping through the elements in a collection using a for-in loop

Issue with IE 11 Console Chrome Console Behavior When changing the word 'item' to 'anotherItem' in the loop like so: var obj = { id1: 'item 1', id2: 'item 2', id3: 'item 3' }; for (anothe ...

Difficulty encountered when trying to template routes with more than one slash in Angular-route

I'm encountering difficulties with my Express+Jade+AngularJS[v1.2.22] application when attempting to access routes such as "mydomain.com/something/somethingelse" or "mydomain.com/something/another/last", which include one or more path subdivisions. T ...

Using JavaScript's if-else statements is akin to a checkbox that is always in its

When working with checkboxes, I can retrieve the state (checked or unchecked) in the browser developer console using $("#blackbox").prop('checked')or $('#blackbox').is(':checked'). I have tried both methods. For example, if I ...

What is preventing the MenuItem component from functioning as a Link in React Material-UI?

Hey there! I've been trying to implement a popover menu that changes the URL and component after clicking on an item, but unfortunately it's not working as expected. I created a setup in this sandbox: https://codesandbox.io/s/romantic-surf-40p19? ...

The JavaScript date picker is malfunctioning in the HTML editor, but it functions properly in Fiddle

I have a working format available in a JS fiddle. Here is the code I have used on my demo site: I created a new folder named "js" and placed datepicker.js inside it, then linked it in my HTML like this: <script type="text/javascript" src="js/datepicke ...

Angular error: Trying to assign a value of type ArrayBuffer to a string type

Is there a way to display a preview of a selected image before uploading it to the server? Here is an example in HTML: <div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)"> <p>drag one or more files to ...

Encountering a TypeError message stating: "list indices must be integers or slices, not list," while attempting to insert JSON data into a

When attempting to insert JSON data into a PostgreSQL database, the following error is encountered: data = response.json()[['data']] TypeError: list indices must be integers or slices, not list def main(): headers = { response = r ...

Discovering the method to incorporate a data-icon attribute within select options using vue.js

UPDATE before modification dataIcon: " @/images/flag-ukraine.svg" after modification dataIcon: require("@/assets/svg/flag-ukraine.svg"), notable change with require() I am using Materialize CSS select. When I use a URL for dataIcon ...

retrieving data from a php file using ajax for a post request

Utilizing ajax, I have invoked the page search.php: function search(){ var title=$("#search").val(); if(title!=""){ $.ajax({ type:"post", url:"sear ...

The system encountered an error while attempting to access the property "getChild" of an unspecified object

I am currently developing a react application and encountering an issue when trying to call a function from the render method. The function I'm trying to call utilizes the getChild method, but I keep receiving an error stating "cannot read property &a ...

React not functioning properly when packaged with Webpack

I tried implementing React in the simplest way possible, but I am facing some issues. After bundling React and opening the index.html page, it shows up completely blank with no console errors to indicate any mistakes. Below is my webpack.config.js: const ...

First render does not define useEffect

Why am I experiencing an issue here? Whenever I attempt to retrieve data from my API, it initially returns undefined during the first render, but subsequent renders work correctly. const [data, setData] = useState([]) useEffect(() => { const fe ...

Ways to Load JSON Content by Directly Pointing to a Node Module

Is it possible to pass variables into a function from a Node module and avoid errors in the response object? Do I need to parse the JSON data? This is what I have tried: app.js var customer = require('./customer'); customer.createCustomer({ ...

What is the best way to reference a div link from a different PHP file?

Struggling to access a page div from another php file, I've tried calling it using (found online) admin.php#changepass Here's an example of my HTML code: <div id="changepass" class="w3-container city" style="display:none"> <form name ...

The jQuery AJAX request is not returning a truthy value when parsing

On my website, I am dealing with a large form and using the serialize() method to process it. However, I have encountered an issue: After completing the form, the result always returns false. I checked this using Firebug. Even though data.ok == true has ...

Retrieving a variable value from an AJAX call for external use

Looking for a solution to pass the generated JSON response from an ASMX web service accessed via AJAX to an outside variable in another function. Below is the code snippet for reference: function setJsonSer() { var strWsUrl = &apo ...

Retrieve the body's coordinates when dragging an element using the jQuery UI library

How can I obtain the coordinates of a dragged div upon drag and drop action, including left, right, and top positions? Additionally, how do I then use Ajax to post these coordinates? An example link can be found at jsfiddle.net/qPw92 <html> &l ...

Error Occurs While Getting Request Parameters with Ajax Post and Express.js

When utilizing ajax to send data from a JavaScript frontend to an Express.js backend server, I am having trouble retrieving the posted data in the API method of my express.js. Below is the code where I attempt to parse the request data. Your assistance i ...