Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

72
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda