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 echo tag. For example:

  • <?php $phpvar = "FOO"; ?>
  • var jsvar = "<?=$phpvar?>";

But there are more 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.

 

 

TLDR – QUICK SLIDES

 

TABLE OF CONTENTS

 

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) USE PHP TO ECHO JAVASCRIPT

1A) ECHO JAVASCRIPT CODE

1-echo-js.php
<!-- (A) PHP VARIABLE -->
<?php $phpvar = "Foo"; ?>
 
<!-- (B) USE PHP TO ECHO JAVASCRIPT CODE -->
<script>
<?php 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 a block of Javascript code – It will be interpreted by the browser just fine.

 

1B) PHP SHORT ECHO TAG TO “INSERT VALUE

1b-short-echo.php
<!-- (A) PHP VARIABLE -->
<?php $phpvar = "Foo"; ?>
 
<!-- (B) PHP SHORT ECHO TAG TO ECHO VARIABLE -->
<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 2) INSERT PHP VARIABLE INTO HTML FORM

2-input.php
<!-- (A) PHP VARIABLE -->
<?php $phpvar = "Foo"; ?>
 
<!-- (B) INSERT INTO HTML FORM -->
<form onsubmit="return demo()">
  <input type="text" id="myTxt" value="<?=$phpvar?>">
  <input type="submit" value="Go">
</form>
 
<!-- (C) JS GET FIELD VALUE -->
<script>
function demo () {
  // (C1) GET FIELD VALUE
  var jsvar = document.getElementById("myTxt").value;
  console.log(jsvar);
 
  // (C2) PREVENT FORM SUBMIT
  return false;
}
</script>

We are still using the PHP short echo tag here, but “inserting” the value into an HTML <input> field and using Javascript to get the form field. Kind of a roundabout way, but this makes sense if you are working with forms.

 

EXAMPLE 3) USE JSON TO PASS ARRAYS

3-json.php
<?php
// (A) PHP CONVERT ARRAY TO STRING
$phpvar = json_encode(["Apple", "Banana", "Cherry"]);
?>
 
<!-- (B) JAVASCRIPT CONVERT STRING TO ARRAY -->
<script>
var jsvar = JSON.parse('<?=$phpvar?>');
console.log(jsvar);
</script>

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

  1. Use json_encode() in PHP to turn the array into a JSON encoded string.
  2. Good old PHP short echo tag to output the string, but coupled with Javascript JSON.parse() to turn the JSON encoded string back into an array.

Quick extra note and summary:

  • JSON stands for “Javascript Standard Object Notation”. A way to represent arrays and objects as strings.
  • PHP –
    • json_encode() turns an array into a 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 an array.

 

 

EXAMPLE 4) AJAX TO FETCH VALUES

4A) HTML & JAVASCRIPT
4a-ajax.html
<!-- (A) AJAX FETCH DATA FROM SERVER -->
<script>
function doAJAX () {
  fetch("4b-ajax.php")
  .then(res => res.text())
  .then(data => {
    console.log(data);
  });
}
</script>
 
<!-- (B) GO! -->
<input type="button" value="AJAX Fetch" onclick="doAJAX()">

If you have not heard it, 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(res => res.text())
  • Lastly, do whatever you need with the data .then(data => { console.log(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.

 

4B) SERVER-SIDE PHP

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

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

 

 

EXAMPLE 5) JSON & AJAX TO PASS ARRAYS

5A) HTML & JAVASCRIPT

5a-ajax-json.html
<!-- (A) AJAX FETCH DATA FROM SERVER -->
<script>
function doAJAX () {
  fetch("5b-ajax.php")
  .then(res => res.json())
  .then(data => {
    console.log(data);
  });
}
</script>
 
<!-- (B) GO! -->
<input type="button" value="AJAX Fetch" 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(res => res.json()).

 

5B) THE PHP

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

This should be self-explanatory by now, we use json_encode() to output the array as a string.

 

EXTRA 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

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.