How to Pass Variables from PHP to JavaScript

If you need to pass dynamically generated PHP variable to JavaScript this snippet is just for you.

How to Pass Variables with json_encode()


This is the easiest way to pass a variable from PHP to JavaScript. You just define the PHP variable, then echo it into a basic JavaScript variable declaration statement.

Remember that the PHP variable needs to be defined before the JavaScript one.

Let's consider we have the following variable in PHP:

<?php
$name = 'John' ;
?>

And we want to pass it to a JavaScript variable called name. Here we go:

<script>
'var name = <?php echo json_encode($name); ?>;
</script>'
Recommendation: This method is easy to implement and understand. Variables are outputted directly to JavaScript, so the DOM is not affected.
Note: PHP has no trivial JavaScript escape functions, and they aren't trivial to implement.

How to Use AJAX to Pass Variables from PHP to JavaScript


This method passes the variable from JavaScript to PHP without reloading the page. This method is considered the best because server and client-side scripts are entirely separate.

To use AJAX, you need two pages, first is where PHP produces the output, and the second is where JavaScript gets that output:

  • get-data.php
/* Do some operation here, like talk to the database, the file-session 
* The world beyond, limbo, the city of shimmers, and Canada. 
* 
* AJAX generally uses strings, but you can output JSON, HTML and XML as well.
* It all depends on the Content-type header that you send with your AJAX 
* request. */ 
echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d. 

                     //You can json_encode() any value in PHP, arrays,                             
                     strings, //even objects.
  • index.php (or whatever the actual page is named like)
<!-- snip →
 <script> 
     function reqListener () { 
        console.log(this.responseText); 
     } 
     var oReq = new XMLHttpRequest(); //New request object 
     oReq.onload = function() { 
          //This is where you handle what to do with the response. 
          //The actual data is found on this.responseText
         alert(this.responseText); //Will alert: 42 
     }; 
     oReq.open("get", "get-data.php", true); 
// ^ Don't block the rest of the execution. 
// Don't wait until the request finishes to // continue. 
oReq.send(); 
</script> 
<!-- snip -->

The result for the given combination of the two files will be 42 when the file finishes loading.

Recommendation: With Ajax, you get more readable code on both languages without mixing JS and PHP. Recommendation: Data is not directly found on the markup, which means that your markup is kept clean of any additional data, and the only JavaScript sees it.
Note: The data generated via a separate HTTP request won't include any information from the HTTP request that generated the HTML document. If you have ruled out embedding the data in the page, it limits you to cookies/sessions.

Echo the Data and Use JavaScript to Get the Information from the DOM


This method is not better than AJAX, but it has its advantages. It's still relatively separated between PHP and JavaScript in a way that there is no PHP right in the JavaScript.

This will create an element which will not be shown to the user but is recognizable to JavaScript.

  • index.php
<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->
Recommendation: DOM operations are often fast, and you can save and get a lot of data relatively rapidly.
Notes: The data that PHP produces is outputted directly to the HTML source, which means that you might get a “dirty” HTML source.
Notes: It is harder to get structured data, and it’s difficult to separate the PHP and your data logic cleanly.

Do you find this helpful?

Related articles