Run a JavaScript function from a php if statement

Javascript is client-side code, PHP is server-side, so you cannot execute javascript while building the page in PHP.

To execute javascript on the client-side as soon as the page has loaded, one way is to use the body onload handler to call your function:

<?php
echo '<script type="text/javascript">';
echo 'function myFunction(){ /* do_something_in_javascript */ };';
echo '</script>';

if ($value == 1) {
    echo '<BODY onLoad="myFunction()">';
}
?>

Better yet, if you can afford the bandwidth, use jQuery and use $(document).ready():

<?php
if ($value == 1) {
    echo '<script type="text/javascript">';
    echo '$(document).ready(function(){ /* do_something_in_javascript */ });';
    echo '</script>';
}
?>

First of all keep in mind that your PHP code is evaluated on the server, while JavaScript runs in the browser on the client-side. These evaluations happen in different places, at different times. Therefore you cannot call a JavaScript function from PHP.

However with PHP you can render HTML and JavaScript code such that it is only rendered when your PHP condition is true. Maybe you may want to try something like this:

if($value == 1) {
   echo "<script>";
   echo "alert('This is an alert from JavaScript!');";
   echo "</script>";
} 

Tags:

Javascript

Php