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!
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?
I am using this script:
var obj = JSON.parse('');
window.console.log(obj);
Got it. I needed to insert this PHP code in the JSON.parse argument:
json_encode(get_object_vars($object))
Maybe an old post, but still useful 😀
I’m glad you got it working Rob!!
Thanks for responding and letting us know how you got it working!
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
thanks !
What if you want to return back nested objects, that means if you want to return objects having properties as an object with properties, or associative arrays.
I would think it should work the same way as long as you are passing an object and JSON.