How to Pass an Object from PHP to Javascript and Back Again Using JSON

Many times I would like to pass an object from my PHP code to Javascript or from Javascript to PHP. JSON and a couple of PHP and Javascript functions make that easy!

JSON is JavaScript Object Notation. Basically, it’s a textual way to represent an object.

To demonstrate, I will create a PHP object:

<?php $test = array('red'=>'apple', 'yellow'=>'banana', 'orange'=>'orange', 'peach'=>'peach') ?>

To pass this to javascript, I need to do this:

<script>
var obj = JSON.parse('<?php echo json_encode($test) ?>');
</script>

If I want to view the object in javascript, I can use the alert function inside the <script> tags like this:

alert(obj.toSource());

I can pass the Javascript Object through Ajax or several other ways. Here is one way to pass the object:

<a id="link" href="">go to script 2</a>
<script>
link = document.getElementById('link');
link.setAttribute('href', 'test2.php?j='+JSON.stringify(obj));
</script>

In my test2.php script, I now need to translate the JSON to a php object again:

$var = $_GET['j'];
print_r(json_decode($var));

And there we have it, back in it’s original object form!

9 thoughts on “How to Pass an Object from PHP to Javascript and Back Again Using JSON”

  1. Thanks! This is the most elegant way I’ve seen yet for passing PHP variables to Javascript.

    I wanted to get it working with a true PHP object (not just an array) so that I could browse it in the browser console by opening the disclosure triangles.

    Unfortunately the result is a load of things I am unfamiliar with.. inside ‘Object’ are such things as ‘__proto__’ and many more things – but not the object’s properties that I had hoped to discover.

    Would you know anything about this?

  2. Hi Cindy,

    great stuff. We are currently working on a way to change pdf invoice templates with drag and drop and this is exactly what I am looking.

    Thumbs up !

    Thx

    Jochen

Leave a Comment

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

Scroll to Top