How to fire a JS function inside a PHP IF?

1

Inside PHP has an IF that should execute a JS function.

Thus:     

if ($x == $y) {
    // como executar a função nada() dentro deste if?
}

?>

<script>

function nada() {

    alert("nada de mais");

}
</script>

In short, according to a value obtained from the database, the JS function is executed or not. Why does not this work?

I imagine it might have something to do with Ajax / JSON. Is that it?

    
asked by anonymous 07.03.2018 / 21:13

2 answers

1

You can call the function through a echo :

<?php
if ($x == $y) {
    echo '<script>
    window.onload = function(){ nada(); };
    </script>';
}
?>

<script>
function nada() {

    alert("nada de mais");

}
</script>

If the script is loaded before echo , window.onload is optional:

<script>
function nada() {

    alert("nada de mais");

}
</script>

<?php
if ($x == $y) {
    echo '<script> nada(); </script>';
}
?>
    
07.03.2018 / 21:19
1

I'd say .. do not do that. But anyway.


&lt?php if(foo): ?&gt
    &ltscript&gt bar() &lt/script&gt 
&lt?php endif; ?&gt


&ltscript&gt function bar() { /*do something...*/ } &lt/script&gt
    
07.03.2018 / 21:22