Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda