Lior Goldemberg
Lior Goldemberg

Reputation: 876

getting reference to the clicked button inside an ajax event

I'm looking for a way to get a reference to the caller button/link, inside an ajax event. for example:

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

 function reqListener () {
  console.log(this.responseText);
}

In the reqListener function, to get the button id/class etc.. (I'm talking about cases when isTrusted=true)

Below you can find the load event, as it appears in console. The only reference is to the xhr object itself:

enter image description here

Upvotes: 0

Views: 247

Answers (3)

Lior Paz
Lior Paz

Reputation: 71

I would create a handler for the xhr call with a reference to the button in it's closure. something like this might help: (the get doesn't work in the snippet due to cors)

document.getElementById('btn').addEventListener("click", handleClick);

function handleClick(e) {
  console.log('clicked')
  var oReq = new XMLHttpRequest();
  oReq.onload = console.log;//getReqListener(e.target);
  oReq.open("GET", "https://www.example.com/example.txt");
  oReq.send();

}

function getReqListener(target) {
  console.log('getreq')
  return function(data) {
    console.log('fetched');
    console.log(target.text)
    console.log(data)
  }
}
<button id="btn">click me</button>

Upvotes: 1

Adam Tal
Adam Tal

Reputation: 5961

Sounds like you're doing something you shouldn't be doing.

For such cases, you should usually use some (bad) workaround unless you can get the access to the code that's executing the XHR request.

Some workarounds you can consider:

  1. Look at the document.activeElement hoping the link/button didn't lose the focus so fast.
  2. Add a global event listener for all a, input[type=button], button onclick events and register the last clicked element somewhere on the root element (window in a webpage). This depends if you're using some 3rd party library and you should consider the case of new elements being added to the DOM after your event registration finished.

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175017

Unless the button is exposed to you in a closure, there's no way for you to get it, it is out of scope.

You are basically asking

function foo(cb) {
  const btn = 'You can\'t get me!';
  cb();
}

foo(() => { /* How can I get the value of btn here? */ });

That's not possible.

Upvotes: 0

Related Questions