How to execute two javascript functions in PHP page loading?

0

I have two javascript functions that should be executed when loading the page in PHP. Both are similar. Here is one of them:

<?php
if ($idAluno == $idRespA) {

    echo '<script> window.onload = function(){ funcaoA() }; </script>';

} else {

    $respA = $db->select('tbl_pessoas',['*'],['id'=>$idRespA]);

}
?>

The second part is the same. It only changes the IF, which compares with another variable and if it runs the B () function. But it's pretty much the same thing. Both are executed at the start of the page, one after the other.

The problem is that running it only works the 'window.onload' of one of them. So I guess this should not be the best way to run a JS at startup.

How would a JS run within PHP's IFs at page startup?

They also told me that it is not good to execute JS functions directly in PHP. Why?

    
asked by anonymous 08.03.2018 / 00:23

2 answers

0

Solved with jQuery. So:

<?php
if ($idAluno == $idRespA) {

    echo '
    <script>
        $(document).ready(function() {
            funcaoA();
    });

    </script>
    ';

} else {

    $respA = $db->select('tbl_pessoas',['*'],['id'=>$idRespA]);

}
?>

As said, just below is another "if" very similar to the one above. Like the first one, it executes the function corresponding to it (the "functionA" for the first "if" and the "functionB" for the second "if"). Now both have the expected operation.

Thank you all!

    
08.03.2018 / 17:55
0

You can user window.addEventListener("load",... more than once:

<?php
if ($x == $y) {
    echo '<script>
    window.addEventListener("load",function(){
       funcaoA();
    });
    </script>';
}

if ($a == $b) {
    echo '<script>
    window.addEventListener("load",function(){
       funcaoB();
    });
    </script>';
}
?>

As for calling JS functions via PHP I do not see any problems. PHP only returns HTML code for the browser. What you need to be careful about is validate variables that will allow the script to be written and run in the browser. But that's another department.

    
08.03.2018 / 00:35