Home » Php » Run a JavaScript function from a php if statement

Run a JavaScript function from a php if statement

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am using PHP conditions and want to know if I can run a JavaScript function without some one have to click on it using JavaScript:

if($value == 1)     
{  
    JavaScript to run the function  
}

How would I do that?

How to&Answers:

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>";
} 

Answer:

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>';
}
?>

Answer:

I’ve found that you cannot do something like this in IE and other browsers. It does work in Firefox though. You have to echo out each line as posted in the other method.

<?php
if(somecondition)
  {
?>

<script>
Some javascript code
</script>

<?php
  }
?>

Answer:

I know this thread is old but I just came across it and wanted to add my technique.

You can also echo the php variable into JavaScript and do something based on its value. I use it to place database values into js so the user can do math on the page with them

    <script>
var jsvar = <?php echo $phpvar ;?>
if (jsvar = x){ do something...}
</script>

Answer:

After some tinkering, I was able to get the following to work within a .php file.
This doesn’t work in a .html file though.

<?php
if (isset($_SESSION['loggedin'])) {$login='t';}else{$login='f';}
?>

<script>
var login = "<?php echo $login ?>";
console.log(login);

if (login == 'f'){ .. do something..}