The XMLHttpRequest onload() function is failing to pass an instance of the XMLHttpRequest object

I am facing an issue with a function that sends a basic AJAX request to my server. The JavaScript code in the browser is as follows:

function testRequest() {

    var xhr = new XMLHttpRequest();
    xhr.onload = () => {

        console.log("RESPONSE RECIEVED");
        console.log(this); // 'this' should be a XMLHttpRequest object
        console.log(this.status);
        console.log(this.responseText);
    };

    xhr.open('POST', `http://server_ip/test`, true);
    xhr.send();
}

The server-side code (using Express.js) looks like this:

app.post("/test", (req, res) => { 

    res.setHeader("Access-Control-Allow-Origin", "*");
    res.status(200).send("testing");
});

Upon calling the function, the response I'm receiving on the browser console is different from what I expected. Here's what it shows:

RESPONSE RECEIVED
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}

undefined

Instead of getting the desired output:

RESPONSE RECEIVED
XMLHttpRequest {…}
200
"testing"

This means that the browser seems to receive the server response but for some reason, the 'this' object passed into the onload function appears to be a 'Window' object rather than an 'XMLHttpRequest' object. As a result, the status and responseText variables are not accessible.

Upon inspecting the request in the browser, the response body does contain the expected 'testing' data.

Answer №1

The reason for this behavior is due to the use of an arrow function () =>. In arrow functions, the this keyword is captured lexically and does not change with the context in which it is used. In your scenario, the this is referring to the window context because that is the outermost lexical scope where it was declared.

To resolve this issue, you should convert the arrow function into a regular function so that this points to the xhr object:

xhr.onload = function(){
      console.log("RESPONSE RECEIVED");
      console.log(this); // 'this' should be an XMLHttpRequest object
      console.log(this.status);
      console.log(this.responseText);
};

According to the MDN documentation:

An arrow function does not have its own instance of this. Instead, it uses the value of this from the surrounding lexical scope; arrow functions adhere to standard variable lookup rules. Therefore, if a reference to this cannot be found within the current scope, an arrow function will inherit the value of this from its parent scope.

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 is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

Guide on removing material-ui from your project and updating to the newest version of MUI

I need to update my React app's material-ui package to the latest version. Can someone provide instructions on how to uninstall the old version and install the new MUI? UPDATED: In my package.json file, the current dependencies are listed as: ...

Executing a JavaScript function to submit an HTML form and circumvent the default behavior

Currently, I am utilizing a virtual keyboard that was created using JavaScript for the user interface on an embedded system. If you would like to access the source code for this virtual keyboard, you can find it here: https://codepen.io/dcode-software/pen ...

What is the process for populating a checkbox with data from a configuration file using JavaScript?

I have a requirement where I need to populate a list of checkboxes with data from a configuration file. To elaborate, if my checkboxes are meant to select sports, within my JSON configuration file I have an array like this: sports: ["Tennis", "Rugby", "S ...

Retrieving the path parameter in a Next.js APIabstractmethod

I need assistance with extracting information from the file routes/api/[slug]/[uid].ts Specifically, I am looking to retrieve the slug and uid within my handler function. Can anyone provide guidance on how to achieve this? ...

Struggling to access the Angular Route

I am facing an issue where I can't seem to open the route "/d", while "/" is working perfectly fine. I have tried various troubleshooting methods but unfortunately, haven't been able to find a solution yet. var myApp = angular.module('myApp ...

Spinning text within a circular rotation in CSS

Looking for guidance on how to center the "hallo" text inside a circle? Currently experiencing issues with the circle display in IE8 and Firefox. Any suggestions on how to fix this would be greatly appreciated. And here is the link to my code snippet: CSS ...

Use jQuery to swap out images and witness the image loading in real time

Currently, I am using jQuery to dynamically change images by using the code $('img').attr('src','newUrl'); However, whenever I do this, the image is only displayed once it has completely loaded. Due to my slow internet conne ...

Incorporating Products from an Iframe into the Cart on Woocommerce

I recently set up a store using WooCommerce, and I have a unique situation where my customizable products are displayed within an iframe. The "add to cart" button is also contained in this iframe. Whenever I click on the Add to Cart button, I receive a mes ...

Automatically log users out of Django and update the backend after a period of inactivity without requiring any additional requests

In my Django project, I am working on a simple multiplayer system where I need to update the isCurrentlyActive value in a user-related model automatically and then log them out. I tried using middleware following a solution from this post, which works well ...

Execute a function on a canvas timer using the setTimeout method

I'm having an issue with my setTimeout function in this code. I want it to call a timer function for a delay, but it's not working consistently every second. Why is that happening? <head> <script> function timer(sec) { var c = do ...

Load images in advance using jQuery to ensure they are cached and retrieve their original sizes before other activities can proceed

When a user clicks on a thumbnail, I aim to display the full-size image in a div. To achieve this, I want to determine the original size of the image based on its source URL before it loads, allowing me to set the appropriate dimensions for the container. ...

Issue: TypeError: Unable to access the 'getBoundingClientRect' property of an undefined value

Is there anyone who can lend me a hand? I encountered an issue: TypeError: Cannot read property 'getBoundingClientRect' of null https://i.stack.imgur.com/Jnfox.png Here is the code snippet I am trying to render: <div className="box&qu ...

Guide on executing YUI tests in headless mode and recording outcomes in a log document

I currently have some YUI tests that I need to run in headless mode. Right now, these tests are executed by launching their corresponding TestFileName.html. As a result, the browser displays the test results with green and red icons along with messages ind ...

Pressing the submit button will trigger the execution of a .php script, which will then generate a popup on the screen and refresh a specific part of

I have a select form and submit button on my page, which are dynamically generated based on entries in the database. Here is the HTML output: <div id="structures"> <h1>Build</h1> <form name="buildForm" id="buildForm" method="POST" ons ...

How can you efficiently cache a component fetching data from an API periodically in React?

I have a situation where I need to continuously fetch data from an API at intervals because of API limitations. However, I only want to update the state of my component if the API response is different from the previous one. This component serves as the m ...

Transferring local variables to partial templates

Currently, I have set up a display of multiple posts along with a 'Like' form for each post. While everything runs smoothly using format.html, there seems to be an issue when attempting to use Ajax: A NameError is triggered (undefined local va ...

Instructions for designing a Loading Indicator or Progress Bar within the App Directory of NextJS

Having built a substantial web application using NextJS 13, I initially utilized the Pages Router. However, as I neared completion of the website, I decided to make the switch to the App Directory. The primary motivation behind this migration was not just ...

Php file not receiving data from ajax post method

forget.php PHP: if (! (empty($_POST['emailforget'])) ) { echo "here in the function"; } else { echo "here"; } AJAX: $("#passreset").on('click', function(e) { var emailforget = $("#tempemail").val(); alert(emailforget); ...

The user session id has been updated to reflect the latest user who logged in using the ajax login feature in CodeIgniter 3

I have encountered an unusual issue with the login functionality on my website. When User A logs in successfully, they are redirected to the homepage with their session data intact. However, when User B logs in, their session overwrites that of User A&apos ...