How to fire a JS function inside a PHP IF?

Asked

Viewed 1,244 times

1

Within PHP you have an IF that should run a JS function.

Thus:

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

?>

<script>

function nada() {

    alert("nada de mais");

}
</script>

Summarizing, according to a value obtained from the database, the JS function is executed or not. Why not run?

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

2 answers

2


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 the echo, the window.onload is optional:

<script>
function nada() {

    alert("nada de mais");

}
</script>

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

1

I would say.. don’t do that. But anyway.


<?php if(foo): ?>
    &ltscript> bar() </script> 
<?php endif; ?>


&ltscript> function bar() { /*do something...*/ } </script>

Browser other questions tagged

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