What is the reason for XMLHttpRequest overwriting preexisting events?

After clicking a button, I trigger an XMLHttpRequest event. However, I noticed that the original event becomes null once the request is sent. Why does this occur? Is there a way to maintain the original event?

document.getElementById('start').addEventListener('click', handler);

function handler(e){
  var req = new XMLHttpRequest();
  var method = 'GET';
  var destination = 'example.com';
  req.open(method, destination);
  req.send();
  
  console.log(e.currentTarget) // displays <button></button>
  
  req.onreadystatechange = function(){
    console.log(e.currentTarget) // shows null!!! Why???
  }
}
<form>
    <button id='start' type='button'>Click</button>
</form>

Answer №1

Give this a shot:


     const handleClick = (e) => {
      const event = e;
      var request = new XMLHttpRequest();
      var method = 'POST';
      var url = 'example.com';
      request.open(method, url);
      request.send();

      console.log(e.currentTarget) // displays correct current target

      request.onreadystatechange = function(){
        console.log(event);
        console.log(event.target) 
      }
    }

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 reason behind using 'dummy' local variables to define return object keys?

I've come across a code similar to the one below on several occasions recently. One thing to observe is that modelMapper, viewMapper, and source are all defined as local variables but are not used anywhere else, except for being keys in the return ob ...

Creating a stand-alone NPM module for a Redux store to be used in a React application

Can the Redux Store be developed as a separate npm package for a React App and then imported into it? For instance: Assuming there is a fictional React Project named reactapp. A package called reactapp-reduxstore is created containing the Redux Store, al ...

issue with AngularJS model not initially binding to select dropdown

I am facing an issue with a select dropdown in my code. I am using ng-repeat to populate the dropdown like this: <select ng-model="tstCtrl.model.value" required> <option ng-repeat="option in tstCtrl.myOptions" value="{{option.a}}">{{option.b ...

Managing PHP multiple follow-up options in HTML select fields

My goal is to design a form that includes multiple follow-up select fields. These fields will be populated from an array with 3 elements: ID, Name, and followingID. The followingID corresponds to an ID in the array, helping us determine the hierarchical la ...

Executing sequential jQuery ajax requests with a REST API

I need a little help and hope you can assist me with my somewhat challenging problem. I have a REST API collection where URL1 provides a list of names, and URL2 contains properties related to the names from URL1 (e.g., URL2?name=URL1.name). Example: URL1 ...

How can refs be applied effectively in React applications?

I've been thinking about the role of refs in React and how they can address certain challenges for developers. However, I have found that the explanations provided in the React documentation are not very clear, and there seems to be a lack of helpful ...

Combine large arrays

Hey, I'm encountering some issues while trying to merge large arrays in a React Native app. Specifically, I am attempting to implement infinite scroll on React Native. The issue arises when the array reaches 500+ items; every time I add more items, my ...

Ways to distinguish jquery response apart from using $.post method?

Using jquery $.post method: $.post( 'includes/studiesAjax/addTryb.php', {inputVL: inputVL}, function(res){ $("#container").html(res); } ); The response contains a long html code. I am interested in extracting data from ...

jQuery Animation: Creative Menu Icon Display

Whenever the toggle menu's navigation icon is clicked, it triggers an animation that transforms the "hamburger" icon into an "X", causing the navigation menu to drop down. If a user clicks either the navigation icon or outside of the active toggle me ...

There appears to be an issue with the compilation of the TypeScript "import { myVar }" syntax in a Node/CommonJS/ES5 application

In my Node application, I have a configuration file that exports some settings as an object like this: // config.js export var config = { serverPort: 8080 } Within another module, I import these settings and try to access the serverPort property: // ...

Bring in Bootstrap and the Carousel plugin using Webpack Encore

Currently, I am tackling an issue within my Symfony project that involves Webpack Encore and the loading of Bootstrap and the Carousel plugin. The problem may stem from how I import Bootstrap, as it seems to partially work when I import the file like this ...

The virtual method 'android.location.Location' was called in error

I'm using WL.Device.Geo.acquirePosition(onGeoLocationSuccess, onGeoLocationFailure, options) from MobileFirst to retrieve a device's location. Initially, everything works smoothly as I successfully obtain the location. However, after clearing t ...

What is the best way to ensure that JavaScript code is executed in a specific sequence?

Even though I understand that Javascript is not the same as C# or PHP, I keep encountering an issue with Javascript - specifically with how I use it. Here's the scenario: function updateStatuses(){ showLoader() //displays 'loader.gif' on ...

Is there a way to dynamically change an icon based on certain conditions using typescript?

I am struggling with displaying icons in my TypeScript code using Material Icons. I need to dynamically change the icon based on a condition, for example if the power is false I want to display 'power_off', but if it's true then I want to di ...

Displaying a clock using PHP

Seeking a way to display server time on my website, I have successfully implemented client-side time using JavaScript. How can I now showcase the server time? Are there any ZendFramework classes that can assist with this? Currently, I am utilizing the fo ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

How can I display JSON data as key-value pairs in ReactJS?

Transitioning from JavaScript to React, I've come across some threads that touch on this topic but none quite hit the mark. I have a local JSON file that was created with a Python script, and it looks something like this: [{"hello": 10, "world": 15 ...

How can you locate the position of a selector within a parent or set using jQuery

Could someone please help me determine the position of the current selector within its parent using jQuery? I need this information in order to effectively use the .insertAfter() and .insertBefore() methods to rearrange elements within their nested structu ...

Generate a JavaScript File/Blob from an image's URI

Can I generate a File or Blob object from an image URI? I am utilizing the Cordova Image Picker plugin in my mobile application to retrieve photo URIs like this: "file:///data/user/0/..../image.jpg" However, I am struggling to create a File or Blob objec ...

Is it possible to save data to a file using React?

As I work on a React web application, the need has arisen to store crucial user data on the client side in a stable manner. Due to the requirement of data stability and the constraint against using Indexed DB, I am considering storing the data as JSON in ...