Coding Triumph

Helpful code snippets & tutorials

How to access PHP variables in JavaScript

In this post, I’ll show two methods you can use to access PHP variables in JavaScript: the short PHP echo tag <?= ?> and AJAX. Let’s see how we can implement that.

Prerequisite:

  1. PHP 5.6 and above
  2. The XMLHttpRequest object

1. The echo <?= ?> tag:

This is the simplest method for passing PHP variables to JavaScript.

<?php
    $simple = 'simple variable';
    $complex = array('more', 'complex', 'object', ['foo', 'bar']);
?>
<script type="text/javascript">
    // for simple variables
    const simple = "<?= $simple; ?>"; # the quotes are important!
    // json_encode() will convert PHP object into a JavaScript object
    const complex = <?= json_encode($complex); ?>;
</script>

Note that this solution works only for top-level scripts (scripts that are executed inside the HTML); it won’t work in external JavaScript files.

2. Using AJAX

AJAX can be used to exchange data between PHP and JavaScript. So if you need a good interaction between the server and frontend, this is the way to go.

# in variables.php
$var = 'Hello, World!';
// The value you want to pass to JavaScript should be json_encode()ed.
// You can json_encode() any value in PHP, arrays, strings, and objects.
echo json_encode($var);

# In your Javascript
<script>
    let my_variable;
    const req = new XMLHttpRequest();
    req.open("GET", "variables.php", true);
    req.onload = function() {
        my_variable = this.responseText;
        // do what you want with the variable...
        console.log(my_variable)
    };
    req.send();
</script>

Unlike the first method, this one works for both top-level scripts and external JavaScript files. The only downside is Latency – AJAX creates an HTTP request, which is carried over the network.

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments