5 Ways To Pass PHP Variables & Arrays To Javascript

Welcome to a tutorial on how to pass PHP variables and arrays to Javascript. PHP is server-side and JavaScript is client-side, so how do we gel them together?

A quick and easy way to pass a variable from PHP to Javascript is to use the short tag. For example:

  • <?php $PHPVAR = "FOO"; ?>
  • var JSVAR = "<?=$PHPVAR?>";

But there are more proper ways to do so, depending on the situation. We will walk through various examples in this guide – Read on to find out!

ⓘ I have included a zip file with all the example code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Passing Variables Useful Bits & Links
The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example code in a zip file – I have released it under the MIT License, so feel free to build on top of it if you want to.

 

PASSING PHP VARIABLES TO JAVASCRIPT

All right, let us now dive into the various ways to pass PHP variables to Javascript.

 

EXAMPLE 1) PHP TO ECHO JAVASCRIPT

1-echo-js.php
<?php
// (A) THIS IS PHP
$phpvar = "Foo Bar";
?>
 
<!-- (B) THIS IS JAVASCRIPT -->
<script>
<?php
// USE PHP TO ECHO JAVASCRIPT CODE
// var jsvar = 'Foo Bar';
echo "var jsvar = '$phpvar';";
?>
console.log(jsvar);
</script> 

Well, this might be a surprise for some beginners, but remember that Javascript is an interpreted language? Yes, we can use PHP to echo blocks of Javascript code – It will be interpreted by the browser just fine.

 

 

EXAMPLE 2) PHP SHORT TAG

2-short-echo.php
<?php
// (A) THIS IS PHP
$phpvar = "Foo Bar";
?>
 
<!-- (B) THIS IS JAVASCRIPT -->
<script>
var jsvar = "<?=$phpvar?>";
console.log(jsvar);
</script>

It is a real pain to do echo "var abc = '$xyz';"; every time, so here is a quick convenience in PHP, the short echo tag <?=$PHPVAR?>. Yep, this is equivalent to doing <?php echo $PHPVAR; ?>.

 

EXAMPLE 3) AJAX TO FETCH VALUES

THE HTML & JAVASCRIPT
3a-ajax.html
<script>
function doAJAX () {
  fetch("3b-ajax.php")
  .then(result => result.text())
  .then((data) => { console.log(data); });
}
</script>
 
<input type="button" value="AJAX demo" onclick="doAJAX()"/>

If you have not heard, AJAX stands for “Asynchronous Javascript and XML”. In simple terms, sending or fetching data from the server without reloading the entire page. AJAX is very easy to perform, and it is probably deemed to be the most “appropriate way to pass variables”.

  • Fetch data from the PHP script – fetch(URL)
  • Then return the results as text .then(result => result.text())
  • Lastly, do whatever you need with the data .then((data) => { alert(data); })

P.S. Take extra note that AJAX will not work with file:// (directly opening the HTML file in the browser). Use a proper web server with http:// instead.

 

 

SERVER-SIDE PHP

3b-ajax.php
<?php
$phpvar = "Foo Bar";
echo $phpvar;

On the server-side, just do whatever PHP processing and output it, this will be picked up in the AJAX call – result => result.text().

 

EXAMPLE 4) JSON TO PASS ARRAYS

4-JSON-escape.php
<?php
// (A) CONVERT ARRAY TO STRING
$data = ["Apple", "Banana", "Cherry"];
$encoded = json_encode($data);
?>
 
<!-- (B) THIS IS JAVASCRIPT -->
<script>
// (B1) JSON ENCODED STRING
var encoded = '<?=$encoded?>';
console.log(encoded); // STRING
 
// (B2) JSON PARSE (DECODE)
var data = JSON.parse(encoded);
console.log(data); // ARRAY
</script>

Sadly, we cannot pass an array (or object) as-it-is. In this case, we can:

  • (A) Use json_encode() in PHP to turn the array into a JSON encoded string.
  • (B1) Good old PHP short tag to output the string.
  • (B2) Use JSON.parse() to turn the JSON encoded string back into an array.
  • Quick extra note and summary:
    • PHP – json_encode() turns an array into string, json_decode() turns the JSON string back to an array.
    • Javascript – JSON.stringify() turns an array into a string, JSON.parse() turns string back to array.

 

EXAMPLE 5) JSON & AJAX TO PASS ARRAYS

THE HTML & JAVASCRIPT

5a-ajax-json.html
<script>
function doAJAX () {
  fetch("5b-ajax.php")
  .then(result => result.json())
  .then((data) => { console.log(data); });
}
</script>
 
<input type="button" value="AJAX demo" onclick="doAJAX()"/>

Still remember “AJAX fetch” from earlier? This is the same, except that we tell fetch() to parse and return the results as JSON data – .then(result => result.json()).

 

 

THE PHP

5b-ajax.php
<?php
$data = ["Apple", "Banana", "Cherry"];
echo json_encode($data);

This should be self-explanatory by now. We use json_encode() to turn an array into a string.

 

USEFUL BITS & LINKS

We are now done with the tutorial, and here are a few links and extras that may be useful.

 

LINKS & REFERENCES

 

YOUTUBE TUTORIAL

 

INFOGRAPHIC CHEAT SHEET

How to Pass PHP Variables to Javascript (Click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *