How to pass php variable value to javascript



Trick:php variable to javascript

This is a short trick on how can you use a php variable in javascript, though php is a server side language and javascipt is client side language.


php and javascript

   Tutorial Details
   Tool : php, jQuery
   Difficulty level : Beginner

This is a short trick on how can you use a php variable in javascript, though php is a server side language and javascipt is client side language.
TRICK:
 It is true that we can't actually use a php variable in javascipt but we can still use it in some or the other way.
The trick is that we have to use php echo to assign a value to a variable and then we can use that variable. Just look at the code below:

<?php
error_reporting(0);  //turn off error reporting
?>
<html>
<head>
<script src="jquery.js"></script>
<script>
   $(document).ready(function(){       
       var timeLeft = '<?php echo 'Hello' ?>';       
       $("#time").html("<p>"+timeLeft+"</p>"); 
    });
</script>
</head>
<body>
<div id="time"></div>
</body>
</html>

Source Code: This is what the source code looks like.
Here first the server side language is executed first. Here echo  assigns the value to the variable. Now our script is a normal script and finally we can use that variable as a simple javascipt variable. 

USE: 
One simple use of such a method is while making a timer we can use the php date function instead of relying on javascipt date function because the timer will not work properly if someone changes his local machine time.

You can also do it the other way:

<?php
error_reporting(0);  //turn off error reporting
?>
<html>
<head>
<script src="jquery.js"></script>
<script>
   $(document).ready(function(){       
   <?php
   echo 'var timeLeft=1500'; 
   ?>      
   $("#time").html("<p>"+timeLeft+"</p>"); 
   });
</script>
</head>
<body>
<div id="time"></div>
</body>
</html>