It is an often asked question on the CakePHP google groups, how to pass a php array to javascript. The answer is to convert the PHP array to JSON, I have seen several solutions recommended which included using vendor classes, the PHP 5 extension for JSON - however the recommended way is to use the 'Object' method of javascript helper. Being a pure PHP solution it works in both PHP 4 as well 5
Using it is as simple as using any other helper, suppose you have some arrays in your controller, just pass them to the view and use.
OK! here is stripped down code snippet with output
Controller code
View code
The output is
-
[1, 2, 3, 4, 5]
-
{"one":1, "two":2, "0":3}
A more complex output from the result of findAll in Cheesecake-Photoblog is shown below.
Resultant JSON
-
[{"Photo":{"id":2, "filename":"1180944624_3dgreen.png", "title":"3D Green", "created":"2007-06-04 13:40:00"}}, {"Photo":{"id":1, "filename":"1180938295_FreshFlower.jpg", "title":"Fresh Flower", "created":"2007-06-04 11:54:00"}}]
What you now do with the JSON output is entirely upto you
I didn't know it was so simple using the $javascript->Object method, thank you for sharing this it has become useful already.
Nice tip, thanks
Brilliant Tip. I had no idea it was so easy. To think I've been building the arrays myself all this time. Duh.
other than full compatibility, what advantage do I get using this over the native PHP json_encode ?
Great. Very Simple but Effective.
Thanks!
it was a quiet good tutorial.