How to assign a PHP variable to JavaScript?

PHP and JavaScript run at different times in the web development lifecycle. PHP executes on the server before sending HTML to the browser, while JavaScript runs in the browser after receiving the page. This tutorial shows various methods to pass PHP variable values to JavaScript.

Understanding the execution sequence is crucial: PHP processes your .php file first to generate HTML, then sends the processed code to the client's browser. Once in the browser, JavaScript executes, but PHP is no longer accessible.

Using Echo (Direct Assignment)

The simplest method is using PHP's echo to output PHP variables directly into JavaScript when both are on the same page.

Syntax

<?php
   $phpvar = "something";
?>
<script>
   const phpecho = "<?php echo $phpvar; ?>";
   console.log(phpecho);
</script>

Example

<html>
<body>
   <h2>Assigning PHP Variables to JavaScript using Echo</h2>
   <?php
      $phpvar = "I am a PHP variable";
      $intval = 100;
      $arrval = [10, 20, 30];
   ?>
   <div id="output"></div>
   <script>
      const phpecho = "<?php echo $phpvar; ?>";
      const intout = <?php echo $intval; ?>;
      const arrout = <?php echo json_encode($arrval); ?>;
      
      const output = document.getElementById("output");
      let result = "String: " + phpecho + "<br>";
      result += "Integer: " + intout + "<br>";
      result += "Array: " + JSON.stringify(arrout);
      output.innerHTML = result;
   </script>
</body>
</html>

Using Hidden DOM Elements

This method stores PHP data in hidden HTML elements, which JavaScript can then read. It's cleaner than direct echo and useful when you need the data after user interactions.

Syntax

<div id="phpData" style="display: none;">
   <?php
      $color = "Blue";
      echo htmlspecialchars($color);
   ?>
</div>
<script>
   const color = document.getElementById("phpData").textContent;
   console.log(color);
</script>

Example

<html>
<body>
   <h2>Assigning PHP Variables using Hidden DOM Elements</h2>
   <div id="color" style="display: none;">
      <?php
         $color = "Blue";
         echo htmlspecialchars($color);
      ?>
   </div>
   <div id="score" style="display: none;">
      <?php
         $score = 1000;
         echo htmlspecialchars($score);
      ?>
   </div>
   <div id="fruits" style="display: none;">
      <?php
         $fruits = ["Apple", "Orange"];
         echo json_encode($fruits);
      ?>
   </div>
   <div id="result"></div>
   <script>
      const color = document.getElementById("color").textContent;
      const score = document.getElementById("score").textContent;
      const fruits = JSON.parse(document.getElementById("fruits").textContent);
      
      document.getElementById("result").innerHTML = 
         "Color: " + color + " | Score: " + score + " | Fruits: " + fruits.join(", ");
   </script>
</body>
</html>

Using Fetch API (Asynchronous)

The Fetch API allows JavaScript to request PHP data asynchronously. This method is ideal when you need to keep JavaScript and PHP code separate or when data requires complex processing.

Syntax

<script>
   fetch("data.php")
   .then(response => response.json())
   .then(data => {
      console.log(data);
   });
</script>

Example

Create two files: data.php (returns JSON data) and index.php (fetches the data).

data.php:

<?php
   $colorArray = [
      "primary" => "Red",
      "secondary" => "Blue"
   ];
   header('Content-Type: application/json');
   echo json_encode($colorArray);
?>

index.php:

<html>
<body>
   <h2>Assigning PHP Variables using Fetch API</h2>
   <div id="display">Loading...</div>
   <script>
      fetch("data.php")
      .then(response => response.json())
      .then(data => {
         const display = document.getElementById("display");
         display.innerHTML = "Primary: " + data.primary + ", Secondary: " + data.secondary;
      })
      .catch(error => {
         console.error('Error:', error);
      });
   </script>
</body>
</html>

Using Short PHP Echo Tag

PHP provides a shorthand <?= ?> syntax that's equivalent to <?php echo ?>.

Example

<html>
<body>
   <h2>Using Short PHP Echo Tag</h2>
   <div id="result"></div>
   <?php $book = 'JavaScript Tutorial'; ?>
   <script>
      const bookTitle = '<?= $book ?>';
      document.getElementById("result").innerHTML = "Book: " + bookTitle;
   </script>
</body>
</html>

Comparison of Methods

Method Execution Complexity Best Use Case
Direct Echo Synchronous Simple Static data on page load
Hidden DOM Synchronous Medium Data needed after user interactions
Fetch API Asynchronous Complex Dynamic data loading
Short Echo Synchronous Simple Quick variable assignment

Key Considerations

  • Security: Always use htmlspecialchars() for string data to prevent XSS attacks
  • Data Types: Use json_encode() for arrays and objects
  • Performance: Direct echo methods are faster; AJAX methods have network latency
  • Maintenance: Separate files (Fetch API) improve code organization

Conclusion

Choose the method based on your needs: direct echo for simple static data, hidden DOM elements for cleaner separation, and Fetch API for dynamic asynchronous data loading. Always consider security and data type handling when transferring data between PHP and JavaScript.

Updated on: 2026-03-15T23:19:00+05:30

23K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements