Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

64
Views
Javascript returning dataset from function to xmlhttprequest get parameters

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!