Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a JavaScript function from a php if statement

Tags:

javascript

php

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?

like image 864
Asim Zaidi Avatar asked Jun 16 '10 21:06

Asim Zaidi


People also ask

How can I use JavaScript and PHP together?

JavaScript is used as client side to check and verify client details and PHP is server side used to interact with database. In PHP, HTML is used as a string in the code. In order to render it to the browser, we produce JavaScript code as a string in the PHP code.

How call JavaScript function in PHP if condition?

php if(your condition){ echo "<script> window. onload = function() { yourJavascriptFunction(param1, param2); }; </script>"; ?>

Can you run JavaScript on PHP?

You can execute Javascript through PHP by calling javascript code/function as a string in PHP and send it to the client browser to execute.

Can you put an if statement inside an if statement PHP?

Nested If StatementsWe can use if statements inside if statements. These statements are called Nested If Statements.


2 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>";
} 
like image 191
Daniel Vassallo Avatar answered Sep 29 '22 11:09

Daniel Vassallo


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>
like image 40
SuperCatchyUsername Avatar answered Sep 29 '22 11:09

SuperCatchyUsername