How to pass variables and data from PHP to JavaScript ?

In this article, let’s see how to pass data and variables from PHP to Javascript.

We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to perform the operation on the same page. Else we can pass data from PHP to JavaScript using Cookies. Cookie work in client-side.

Program 1: This program passes the variables and data from PHP to JavaScript using assignment operator.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to pass variables and data
        from PHP to JavaScript?
    </title>
</head>
  
<body style="text-align:center;">
      
    <h1 style="color:green;">GeeksforGeeks</h1>
      
    <h4>
        How to pass variables and data
        from PHP to JavaScript?
    </h4>
      
    <?php
        $name = "Hello World";
    ?>
  
    <script type="text/javascript">
        var x = "<?php echo"$name"?>";
        document.write(x);
    </script>
</body>
  
<html>

chevron_right


Output:

Here, we just take input by statically or dynamically and pass it to JavaScript variable using the assignment operator. The PHP code in the JavaScript block will convert it into the resulting output and then pass it to the variable x and then the value of x is printed.

Program 2: This program passes the variables and data from PHP to JavaScript using Cookies.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to pass variables and data
        from PHP to JavaScript?
    </title>
</head>
  
<body style="text-align:center;">
      
    <h1 style="color:green;">GeeksforGeeks</h1>
      
    <h4>
        How to pass variables and data
        from PHP to JavaScript?
    </h4>
      
    <?php
          
        // Initialize cookie name
        $cookie_name = "user";
        $cookie_value = "raj";
          
        // Set cookie
        setcookie($cookie_name, $cookie_value);
          
        if(!isset($_COOKIES[$cookie_name])) {
            print("Cookie created | ");
        }
    ?>
  
    <script type="text/javascript">
        var x = document.cookie;
        document.write(x);
    </script>
</body>
  
<html>

chevron_right


Output:

PHP provides a method to set the cookie using the setCookie() method. Here, we can set the data or variable in PHP cookie and retrieve it from JavaScript using document.cookie.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.