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

I am encountering a JQuery syntax error while using Bootstrap 3 button-dropdown links

I'm trying to replicate the example found here in order to create a similar markup: <div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> ...

How can I use JavaScript to convert a JSON object into an array for iteration with ng-repeat?

Upon retrieving my JSON object from Firebase, I am faced with the challenge of converting a list into an array for binding in HTML using ng-repeat. The structure of my JSON object is as follows: { "cats1": { "Name": "cricket", "imgUrl": "some ...

Develop a JavaScript application that contains a collection of strings, and efficiently sorts them with a time complexity of O(nlog n)

Seeking assistance in developing a JavaScript program that contains an array of strings and must sort them efficiently in O(nlog n) time. Grateful for any guidance... ...

When it comes to AFrame+Three.js, which is more efficient: having numerous meshes with minimal triangles per mesh or having a few meshes with a high number of

Currently working with Aframe 1.0.4 and Three.js 111, I am exploring the performance differences between: Whether it is better to have a few entities with a high number of triangles or many entities with fewer triangles each. Specifically, I am debating ...

The combination of React.js and debouncing on the onChange event seems to be malfunctioning

I recently incorporated a React component that triggers an event on change. Here's how I did it: NewItem = React.createClass({ componentWillMount: function() { this._searchBoxHandler = debounce(this._searchBoxHandler, 500); }, _searchBoxH ...

What is the maximum allowable size for scripts with the type text/json?

I have been attempting to load a JSON string within a script tag with the type text/json, which will be extracted in JavaScript using the script tag Id and converted into a JavaScript Object. In certain scenarios, when dealing with very large data sizes, ...

Is it possible to establish a default route in Next.js?

Is it possible to set up default routes in Next.js so that all routes, or a specific list of routes, will automatically navigate to a designated page? My project involves using Next.js to create the marketing website, as well as the sign-up and sign-in pr ...

My React/Redux App is experiencing difficulties as the state fails to load

Currently, I am working on a project based on the Redux Documentation page. Instead of uploading it directly to Stack Overflow, I decided to share my progress on GitHub: https://github.com/davidreke/reduxDocumentationProject I have completed the instructi ...

"Step-by-step guide on showcasing a specific blog post using its unique identifier in an Angular/Express/MongoDB application

I'm struggling to figure out how to retrieve a single blog post by its ID, especially since I am new to this. Currently, my main blog application has an ng-repeat functionality that fetches all posts. What I really want is the ability to click on a p ...

transferring data from a form with a binary image file to store in an SQL server

I am aiming to create a form where users can upload an image along with some data fields. Currently, I can only get either the image or the data fields to work separately. The following code allows me to upload an image to my SQL database as binary data. I ...

What sets this.prototype apart from module.exports?

As a newcomer to the world of Node.js, I am eager to gather information, experiment with testing techniques, and explore the code written by others. In my exploration, I have noticed that creating and requiring modules is a common practice in Node.js. Dif ...

Tips for displaying personalized error messages from your REST API in a JavaScript client

I'm utilizing a Java REST API that has been generated using swagger. If the client is unauthorized, I am sending custom error messages in response. public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, Str ...

Issue with filtering of values returned by functions

I've been working with Angular's currency filter and I've run into an issue. It doesn't seem to be filtering the data that is returned from a function. I have a feeling that I might be missing something, perhaps it has to do with how th ...

When attempting to run `npm install`, an error message is received indicating a network connectivity issue: "npm ERR

When I try to run npm install, I encounter an error. Here is the error message: 71 error code ETIMEDOUT 72 error errno ETIMEDOUT 73 error network request to https://registry.npmjs.org/@angular%2fanimations failed, reason: connect ETIMEDOUT 151.101.112.16 ...

I'm having trouble receiving a response after uploading an image on Cloudinary using React js

Once the image is uploaded using the API, it should return a response. However, I am not receiving any response through the API even after uploading the image. if (pic.type === "image/jpeg" || pic.type === "image/png") { const da ...

Using Rails to render a partial containing a form object

I need help with rendering a partial called 'colordata' after selecting a color from a dropdown list using Ajax. Unfortunately, I'm not seeing any changes on the main page and the form is undefined in the colordata partial. This is the sche ...

Azure webhosting blocks the use of AJAX calls

There is a PHP script hosted on my Azure server that returns JSON when accessed through the browser. However, I am having trouble making an AJAX call to this script as none of my requests seem to go through. The issue remains unclear. You can see a failed ...

Run code once the Firestore get method has completed its execution

Is it possible to execute code after the get method is finished in JavaScript, similar to how it can be done in Java (Android)? Below is an example of my code: mColRef.get().then(function(querySnapshot){ querySnapshot.forEach(function(doc) { ...

The message will not appear to indicate whether the room is valid or not

Take a look at this create_session.php application: Application Upon opening the application, you will encounter a CourseId textbox. Enter 'info101' in the textbox and click submit. You should see all the features listed below. Without entering ...

Utilizing cookies to track the read status of articles - markers for reference

Currently, I am in the process of developing a website and am interested in implementing a feature that allows users to track which articles they have read. I am considering adding a small circle next to each article heading to signify whether it has been ...