What are the solutions for resolving the TypeError when undefined is not an object error?

I'm currently working on a project where I need to fetch data from a JSON file using XMLHttpRequest and then store it in an array. However, I keep getting errors when attempting to do so.

Take a look at this code snippet that seems to be causing the issue:

var results = [];
var request = new XMLHttpRequest();
request.open("GET", "data.json");
request.onreadystatechange = processData(request, results);
request.send();

function processData(request, results) {
    if (request.readyState == 4 && request.status == 200) {
        var jsonData = JSON.parse(request.responseText);
        results.push(jsonData.data);
        alert(results);
    }
}

The problem appears to occur when trying to access the 'target' value within the function, returning a value of '4' instead.

Answer №1

Incorrect property of request used.

Consider using an inline function for the onreadystatechange callback:

var array = [];
var req = new XMLHttpRequest();
req("get", "test.json");
req.onreadystatechange = function(){
     if ((req.readyState == 4) && (req.status == 200)) {
        var json = JSON.parse(req.responseText);
        array.push(json.test);
        alert(array);
    }
};
req.send();

Alternatively, you can try it your way:

var array = [];
    var req = new XMLHttpRequest();
    req("get", "test.json");
    req.onreadystatechange = handle();
    req.send();
function handle(){
         if ((req.readyState == 4) && (req.status == 200)) {
            var json = JSON.parse(req.responseText);
            array.push(json.test);
            alert(array);
        }
    };

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

JavaScript Game Timer

I am working on a countdown timer where I have set the variable seconds to 10. If the seconds reach zero, I want to add 2 seconds to it and stop the program from looping. Can someone please assist me with this? var isWaiting = false; var isRunning = fal ...

Middleware in Express.js designed to alter the response object

One method I'd like to explore is using middleware functions to alter the response. app.use(function(request, response, next) { .. do something .. next(); // moves to next middleware }); When it comes to modifying the request and response ob ...

distinguishing the container component from the presentational component within react native

I just started developing apps using React Native and implemented a basic login function with the view and login logic on the same page named HomeScreen.js. However, after reading some articles online, I learned that it's recommended to separate the l ...

The fuse-sidebar elements are not being properly highlighted by Introjs

I have recently developed an angular project that utilizes the fuse-sidebar component. Additionally, I am incorporating introjs into the project. While introjs is functioning properly, it does not highlight elements contained within the fuse-sidebar. The ...

Show brief tags all on one line

This image showcases the functionality of the site, specifically in the "Enter a code" column where users can input data using TagsInput. I am seeking to enhance this feature by ensuring that shorter tags are displayed on a single line. While I am aware th ...

What is the process for entering a value into mysql based on the date?

Seeking assistance with a specific coding challenge. The task at hand involves inputting a date, such as '2018-05-08', and based on the user's input, storing the value in different columns of a database table. For instance, if the date is &a ...

AngularJS: Recommendations for structuring code to dynamically update the DOM in response to AJAX requests

Within Angular's documentation, there is a straightforward example provided on their website: function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.order ...

React Router Blank Page Conundrum

In a new project, I'm experiencing an issue where the content is not loading in despite using a similar React-Route setup that worked in a previous project. When I create a nav link in the root directory, it changes the path but the screen remains whi ...

Issue arises when trying to utilize Ajax on the Fancy Box overlay button click and the functionality does not perform as

Hey there! I've got a bit of a silly question for you. So, I'm pretty new to Ajax and fancy box. I've been using fancy box on one of my pages, and it's been working well so far. The issue I ran into was when I tried to make an ajax call ...

Guide on extracting unique identifiers from an array of objects and sorting them by the earliest date in JavaScript

I've got an array of objects and I'm looking to retrieve the items with unique IDs while also selecting the earliest date. For example: [{id:1, date: Jan 12}, {id:2, date: Feb 8}, {id:3, date: Feb 8}] var array = [{id: 1, date: Jan 12 2021 08:00 ...

Utilizing loop variables in ng-class and ng-click directive

This piece of code generates a list consisting of seven thumbnails, with the currently active image designated by the active and thumb classes. <div ng-repeat="no in [1, 2, 3, 4, 5, 6, 7]"> <img ng-src="images/{{no}}t.jpg" class="thumb" ng ...

Issues with the Winston transport for Loggly are causing inconsistent performance

I have implemented Winston with 3 transports: Console, File, and Loggly (using https://github.com/loggly/winston-loggly-bulk). While the Console and File transports are functioning properly, I am facing an issue with the Loggly transport. It only logs my ...

What are the steps to run and test the renovate bot on your local machine

Before setting up renovate to work with my Azure pipeline, I wanted to test it locally using npx renovate to ensure everything is working as expected and that my config file is properly configured. I ran npx renovate --platform local command. My project i ...

Can anyone explain the functionality of passport.initialize() in the context of Node.js and Express

I am currently working on implementing the passport module in my application. After reading some manuals, I found this: app.use(passport.initialize()); app.use(passport.session()); Can someone explain what app.use(passport.initialize()) does exactly? I ...

The outcome of AES encryption varies when comparing Node JS with C# programming languages

In a particular scenario, I need to encrypt and transmit text using the AES 256 algorithm. The decryption process will be handled by client-side C# code. Here is the encryption code in JavaScript: const crypto = require('crypto'); algorithm = ...

The event "subscriptionRemoved" is not being triggered when a password change is made on the Microsoft Graph API

Utilizing the Microsoft Graph API, I have set up subscriptions to receive notifications for calendar events through Node.js. As per the guidelines outlined in the documentation on Enhancing notification reliability for Outlook resources (preview), it speci ...

While attempting to import modules in Visual Studio Code, an error message appears stating "Unexpected token {"

Greetings! I am currently using Visual Code to run my project and would like to share my code with you. In the file external.js: export let keyValue=1000; In the file script.js: import {keyValue} from './external.js'; console.log(keyValue); ...

What is the process for sending Raw Commands to a Receipt Printer using Node.JS?

My Current Project I am currently working on integrating a receipt printer that supports ESC/P raw printing into an app for remote printing of receipts. The Approach I Am Taking To achieve this, I am utilizing the PrintNodes API to send data from my app ...

Leveraging Ajax and jQuery to create a POST request for adding a new record to a MySQL table within a Node.js server

My form is designed to collect user information like name, age, and more. The aim is to submit this data from the client side, inserting it into a MySQL table row. However, I'm facing difficulties in getting the data to successfully insert. Below are ...

Images obscure dropdown menu

The issue I am experiencing with my blog is that the dropdown menu is appearing behind the image slider on the main page. You can see it here: Can anyone offer guidance on how to prevent this from happening so that the dropdown menu is not obscured? Just ...