Home > Software engineering >  call js function from php but property not found
call js function from php but property not found

Time:03-21

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";
}

CodePudding user response:

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>";
    }
}
  • Related