0

I have a data attribute that is populated with a php variable. The php variable is a numeric value.

<?php $userId = 123; ?>
<div class="agent-detail-info" data-id="<?= $userId ?>"></div>

I am trying to grab the value from the dataset and pass it to a get url parameter. I've put this into its own function for window.onload as the php prints the html dynamically.

function userData() {
  let infoWrap = document.querySelector(".agent-detail-info").dataset.id;
  console.log(infoWrap);
  return infoWrap;
}
window.onload = userData;

const request = new XMLHttpRequest();
request.open(
  "GET",
  `url&usertolookup=${userData()}`
);

Console.log(infoWrap) returns the correct value in console, but console shows an error and does not populate the get parameters

Uncaught TypeError: Cannot read properties of null (reading 'dataset') at userData

I'm thinking this is happening because the request is running before the userData function is called and the DOM is not yet populated?

This works:

function userData() {
  let infoWrap = 123;
  return infoWrap;
}

I tried wrapping the request into a function that runs after the DOM is loaded but this also did not work.

jPark197
  • 65
  • 1
  • 7

1 Answers1

1

You should run the code at the end from window.onload, so it runs after the .agent-detail-info element is added to the DOM. Running userData() itself doesn't do anything.

window.onload = () => {
  const request = new XMLHttpRequest();
  request.open(
    "GET",
    `url&usertolookup=${userData()}`
  );
};
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you this definitely answered the question - now I have an issue of chaining functions within the window.onload - Elements are created on the page after the response with the response data and I have a few functions and a function that runs through an inline onclick that call on these elements. Since they are now generated after the dom is loaded these functions are broken. – jPark197 Feb 28 '22 at 21:43
  • I will add the code to the question - the question asked is answered though, thank you – jPark197 Feb 28 '22 at 21:44
  • Everything that depends on DOM elements should be run from the `onload` function. See https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – Barmar Feb 28 '22 at 21:55
  • Thank you.. I am still struggling to get the 3 functions working with an onload.. would you mind taking a look at the code I've appended to the original post? – jPark197 Feb 28 '22 at 22:10
  • Of you have a new problem, post a new question. Don't add to a question that's already been answered. – Barmar Feb 28 '22 at 22:10