How to pass PHP variables to JavaScript

PHP is server side language which retrieves data from database and show in client side. Javascript is client side language which manipulate HTML and data receives from server. So it obviously that you need to pass PHP data into Javascript variables and function.

In this article, we will discuss on 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
    $message = "Hello World!"; // here you get data from database
?>
<!DOCTYPE html>
<html>
<head>
    <title>PHP variable to JavaScript</title>
</head>
<body>
    <h1>PHP variable to JavaScript</h1>    
    <script type="text/javascript">
        var message = "<?php echo"$message"?>";
        alert(message);
    </script>
</body>
</html>

If the PHP data is array or object, first you need to convert it to Json object using json_encode() function. Then you can easily manage Json object in Javascript.

<?php
    $fruits = ['orange' => 'mango', 'yellow' => 'banana', 'red' => 'apple'];
    $json_fruits = json_encode($fruits);
?>
<!DOCTYPE html>
<html>
<head>
    <title>PHP variable to JavaScript</title>
</head>
<body>
    <h1>PHP variable to JavaScript</h1>    
    <script type="text/javascript">
        var fruits = <?php echo($json_fruits)?>;
        alert(fruits.yellow);
    </script>
</body>
</html>

This way, you can pass data from server-side to client-side and manage.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

1 Comment

SA
akhil
September 08, 2021

That was an amazing article, your article gave me more clarity about PHP. It was nice to read your article.