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

135
Vistas
call js function from php but property not found

Uncaught TypeError: Cannot read properties of null when calling js function test(). What is wrong with this example code? Is there a better way to call a js function from php for DOM Manipulation?

html

<form method="post" action="#">
    <input type="text" id="inp">Test</input>
    <button type="submit" id="submit" name="submit" value="submit"></button>
</form>

php

if(isset($_POST['submit')]
{
    $wrongInput= some code...

    if ($wrongInput)
    {
        echo "<script src=main.js></script>";
        echo "<script type=text/javascript>test();</script>"
    }
}

js

function test()
{
    document.querySelector("#submit").style.background = "red";
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Unclear where that is being echoed in the page... But for sure, the DOM needs to be loaded for the querySelector to find the element. So the use of the DOMContentLoaded event is the way to make sure, disregarding where the echo is. ;)

if(isset($_POST['submit')]
{
    $wrongInput= //some code...

    if ($wrongInput)
    {
        echo "<script src='main.js'></script>";
        echo "<script>document.addEventListener('DOMContentLoaded', test);</script>";
    }
}
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