Pass PHP Variables To JavaScript

Pass PHP Variables To JavaScript

Here we will show how you can pass PHP variables to JavaScript and use it into JavaScript function. To do that, you can simply use echo() function into JavaScript variable value.

PHP is server side language which retrieves server and show in client side. JavaScript is client side language which manipulate HTML and data receives from server. So we need to pass PHP data into JavaScript variables and function.

				
					<?php
    $msg = "Hi, everyone!"; 
?>
<!DOCTYPE html>
<html>
<head>
    <title>inflay.com | Pass PHP variable to JavaScript</title>
</head>
<body>
    <h1>Pass PHP variable to JavaScript</h1>    
    <script type="text/javascript">
        var msg = "<?php echo"$msg"?>";
        alert(msg);
    </script>
</body>
</html>
				
			

PHP data is an array or a object than we need  to convert it to Json object format using json_encode() function.

				
					<?php
    $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
    $json_age = json_encode($age);
?>
<!DOCTYPE html>
<html>
<head>
    <title>inflay.com | Pass PHP variable to JavaScript</title>
</head>
<body>
    <h1>Pass PHP variable to JavaScript</h1>    
    <script type="text/javascript">
        var age = <?php echo($json_age)?>;
        alert(age.Ben);
    </script>
</body>
</html>
				
			

I hope this article helps you.
Thanks for visiting Inflay.com .