How to perform two javascript functions when loading the PHP page?

Asked

Viewed 239 times

0

I have two javascript functions that should be executed when loading the page in PHP. Both are similar. Here’s 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 thing. It only changes the IF, which compares with another variable and if it is closed runs the function B(). But it’s pretty much the same thing. Both are executed at page startup, one after the other.

The problem is that when running it only works the 'window.onload' of one of them. So I guess this isn’t the best way to run a JS on startup.

What a way to run JS inside Ifs in PHP on page startup?

I was also told that it is not good to run JS functions directly in PHP. Why?

  • 1

    Tb did not understand why not run a JS function in PHP, since one thing has nothing to do with another. The echo is nothing more than returning an HTML.

  • The onload will only be loaded once. You can create a variable, for example: $script[] = " funcaoA(); " and $script[] = "funcaoB();" and then just use echo "<script>window.onload =&#xA; function() { ".implode("", $script)." }</script>". But avoid doing this. This is gambiarra and may cause you problems in the future.

  • place window.onload = function(){ funcaoA(), funcaoB() }

2 answers

0

May 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 to call for JS functions via PHP see no problem. PHP only returns HTML code for the browser. What you need to be careful about is how to validate the variables that will allow the script to be written and run in the browser. But this is already another department.

  • So it doesn’t work. Because as I said, it’s two IF’s. One for "funcaoA" and one for "funcaoB" (one if after another). When you pass the first IF, "funcaoB" is also executed. And this can only be executed if you pass the second IF.

  • I updated the answer. Abs!

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 spoken, just below has another "if" very similar to the one above. Like the first, it executes or does not the function corresponding to it (the "funcaoA" for the first "if" and the "funcaoB" for the second "if"). Now both have the expected functioning.

Thank you all!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.