How to pass data from PHP to JavaScript

5411 views 9 months ago PHP

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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]