Error encountered while attempting to parse JSON: Unable to access property

Help needed! I've written some code in JavaScript, but it's throwing an error.

function Brain(){
    var request = "request";
    var reply = "reply";
    var words = '';

    this.Reply = function(){
        if(request == words.nouns[0].noun){
            reply = words.nouns[0].noun;
        }
        else {
            reply = this.words.nouns[0].noun;
        }
    }

    this.SetRequest = function(req){
        request = req;
    }

    this.GetReply = function(){
        return reply;
    }

    this.Parse = function(u){
        var xmlhttp = new XMLHttpRequest();
        var url = u;
        var result;
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                words = JSON.parse(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        return result;
    }

    this.Construct = function(){
        words = this.Parse('brain/words.json');
    }}

    var brain = new Brain();
    brain.Parse('brain/words.json');

I am also providing my json file content below:

{
    "nouns": [
        {"noun": "dog"},
        {"noun": "cat"}
    ]
}

Everything works fine in the testing environment, but upon executing the code, an error is thrown:

Uncaught TypeError: Cannot read property 'nouns' of undefined

Answer №1

Your code contains several errors, with the main one being that it does not account for the asynchronous nature of the XMLHttpRequest function. This means it will not return a value in the same way as synchronous functions. To learn more about this issue, you can refer to this resource: How to make a function wait until a callback has been called using node.js. In essence, you need to use a callback function in your parse method to handle the return value instead of relying on a traditional return statement. If this concept is new to you, I recommend researching "javascript callbacks" to understand it better.

Additionally, there are some minor issues in your code such as returning 'result' from 'Parse' without setting it to anything first, and assigning 'words' in multiple places in a confusing manner. These problems can be resolved once you address the synchronization and asynchrony issues.

EDIT:

The suggested fix involves modifying your code as follows:

this.Parse = function(u, callback){ // introducing the "callback" parameter
    var xmlhttp = new XMLHttpRequest();
    var url = u;
    var result;
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            words = JSON.parse(xmlhttp.responseText);
            callback(null, words); // passing the words to the callback function
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
    // no return statement here!
}

this.Construct = function(){
    this.Parse('mind/words.json', function(error, words) {
        // utilize the retrieved words here
    });
}}

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 are the best ways to personalize my code using Angular Devextreme?

Our development team is currently utilizing Angular for the front-end framework and ASP.net for the back-end framework. They are also incorporating Devextreme and Devexpress as libraries, or similar tools. However, there seems to be difficulty in implement ...

Run Javascript code if a specific CSS class is present on an element

Whenever a user enters an incorrect value into a textbox on my page, an error message is displayed within a div with the class 'validation-errors'. I'm looking for a solution to trigger a javascript function (which adds a CSS property to a ...

"Enhance input functionality by updating the value of the text input or resizing the textbox

I've been facing a challenge with updating the value of my input type=text or textbox control text value using jQuery $(window).resize(function(){});. I am aware that the event is triggered because an alert pops up when I resize the browser. Additiona ...

Obtaining information from an AngularJS Service Response and assigning it to the Controller Scope Object

I have a basic AngularJS 1.7 application where I am successfully fetching data from a web API using an AngularJS service. However, I am running into an issue where the data is not being populated in the controller scope object. I have verified that the dat ...

Refreshing a jsp page without the need to reload the content

On my jsp page, I am displaying the contents of a constantly changing table. This means that users have to refresh the page every time they want to see updated information. Is there a way for me to update the content dynamically without requiring users t ...

Create a debounced and chunked asynchronous queue system that utilizes streams

As someone who is new to the concept of reactive programming, I find myself wondering if there exists a more elegant approach for creating a debounced chunked async queue. But what exactly is a debounced chunked async queue? While the name might need some ...

I am looking to optimize my custom tailwindcss file by reducing its size

Here is the structure of my package.json file. "scripts": { "start": "yarn run watch-css && craco start", "build": "yarn run build-css && craco build", "test": "craco test ...

What is the process for applying a class in jQuery to empty HTML elements?

Working on a WordPress/PHP website and looking to dynamically add a class when child elements are empty? This is the HTML structure: <div class="featured-block"> <a href="/" class="featured-block__item cf"> <div class="featured-bl ...

Tips for creating a unique exception in AngularJS?

I have a customException.js script with the following service: app.service('CustomException', function() { this.CustomException1 = function (message) { if (!message) { message = "Custom Exception 1 occurred!"; } return { ...

Empty body detected in Jquery AJAX request with Django REST running in a Docker environment

Using JavaScript to load a template called index.html from the /static directory. The JavaScript code in app.js: var obj = new Object(); obj.startTime = "123"; obj.endTime = "456"; console.log("fetchNext "+JSON.stringify(obj)); v ...

code snippet for callback function in javascript

Recently, I've been working on a project with angularjs and phonegap and stumbled upon this interesting code snippet. While I have a basic understanding of what it does, the inner workings are still a bit unclear to me. Since I'm still getting fa ...

Nested Angular click events triggering within each other

In my page layout, I have set up the following configuration. https://i.stack.imgur.com/t7Mx4.png When I select the main box of a division, it becomes highlighted, and the related department and teams are updated in the tabs on the right. However, I also ...

Retrieve the value of an AngularJS expression and display it in a window alert using AngularJS

Hey there, I am in the process of trying to display the value of an expression using AngularJs As a beginner in angular, I am working on figuring out how to retrieve the value of the expression either with an alert or in the console. I'm utilizing A ...

Issue with Javascript form submission leading to incorrect outcomes

When setting the form action to a text retrieved from the database with an ID, I encountered a problem where it always displays the first ID even when clicking on text holding ID=2. Upon checking the page source, the correct IDs are shown for all texts. B ...

Can context be passed into a component that is created using ReactDOM.render()?

TL;DR In this given example code: ReactDOM.render(<MyComponent prop1={someVar} />, someDomNode); Can one manually provide React context to the instance of MyComponent? This might seem like an unusual question considering React's usual behavio ...

Customizing the Steps Component in Ant Design

Currently, I am utilizing the Steps component from Ant Design. My goal is to enhance its functionality by adding additional components, like a button placed next to each step's description to make it more interactive. Furthermore, I am looking to inc ...

Tips for creating AngularJS nested transcludes

I'm currently delving into the world of angular directives/transclusion to manage the creation of custom panels within my application. Unfortunately, I seem to have hit a roadblock as the transcluded content is not displaying in the HTML. Below is th ...

Preventing dragging in Vis.js nodes after a double click: a definitive guide

Working with my Vis.js network, I have set up an event listener to capture double clicks on a node. ISSUE: After double-clicking a node, it unexpectedly starts dragging and remains attached to the mouse cursor until clicked again. How can I prevent this b ...

How can I create spacing between squares in an HTML div element?

Currently, I am working on my project using Laravel 5. I retrieve some integer values from a database and use them to create square divs in HTML. Below is the current output of my work. https://i.stack.imgur.com/sy2ru.png You may notice that there is spa ...

Exploring the power of jQuery.grep for locating specific keywords and phrases

Struggling to figure out how to extract keywords and phrases from a textarea by using jQuery.grep in a way that does not require an exact match but rather checks if it contains specific keyword(s) and/or phrase(s) in an array. Currently, the code provided ...