Home > Software engineering >  Javascript returning dataset from function to xmlhttprequest get parameters
Javascript returning dataset from function to xmlhttprequest get parameters

Time:03-01

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

<?php $userId = 123; ?>
<div  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.

CodePudding user response:

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()}`
  );
};

  • Related