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

152
Vistas
How to create a dynamic Javascript Variable from a PHP String

How can I create a dynamic Javascript variable using a PHP String?

This approach doesn't work. How should I fix it to make it work?

<?php 
    $dynamicHTMLElementId = rand();
?>

<script type="text/javascript">
    var dynamicHTMLElementId = window[<?php echo json_encode($dynamicHTMLElementId); ?>];
</script>

Thank you all in advance.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Your attempt is almost correct. Of course, for example window[1029376] is not a valid object property of window.
As long as your PHP output is JavaScript syntax it will work.

If your code has the purpose to select a random element (as unrealistic as that is), use document.getElementById() for IDs or the other getElementBy... functions.

<?php 
    $dynamicHTMLElementId = rand();
?>

<script type="text/javascript">
    var dynamicHTMLElement = document.getElementById('<?php echo json_encode($dynamicHTMLElementId); ?>');
</script>

This may result in (with the ID being random):

<script type="text/javascript">
    var dynamicHTMLElement = document.getElementById('1335407484');
</script>

Simply look at the source code of the output and check the browser console for errors.
Be aware that json_encode will not output quotes for a number.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Simple PHP function to initilize a PHP associate array as a JSON object in javascript.

function echoVariableInJavascript($variablename,$variable)
{
   echo("<script type=\"text/javascript\">");
   echo("var ".$variablename."= JSON.parse(atob(\"".base64_encode(json_encode($variable))."\"));");
   echo("</script>");
}

/*Usage*/
$object = ["ok"=>true,"status"=>"Good"];
echoVariableInJavascript("object", $object);
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