JSON output with CakePHP
If you are doing some AJAX development there is a very good chance that you’d like to output your data in a JSON format.
Let’s say that we would like to output all of our user’s data (User model) as JSON. Well, like many other things, it couldn’t be easier with CakePHP.
Let’s create a new action called viewAllJson in our users controller…
function viewAllJson() {
$this->layout = 'ajax';
$users = $this->User->find('all', array('restrict'=>array()));
$this->set('users', $users);
}
This should be pretty much self explanatory. You are using the default AJAX layout, which should be just a blank page, since all you need is the output of the JSON data (no other HTML/text should be present). You are finding all Users and then setting the resulting array for the view. Note, that I’m using the Bindable behavior, hence the use of the ‘restrict’ key (you might need to change that if you don’t use Bindable).
Now we need to create a view (view_all_json.ctp) so that we can display the JSON data.
<?php
Configure::write('debug', 0);
echo $javascript->object($users);
?>
We are utilizing the object method here (refer to the CakePHP’s API for more details on it) in order to generate the JSON from our data array. And really that’s all there is to it.
If you use RequestHandler component, there is no need of calling the Ajax layout, it will be automagically loaded in every ajax call.
Comment by Martin Bavio — May 7, 2008 @ 2:40 pm
@ Martin Bavio
Thanks, good point.
Comment by teknoid — May 7, 2008 @ 3:24 pm
I always put my debug in 0 into core, thanks for this tip.
Comment by Webmaster Mexico — June 4, 2008 @ 4:39 am
@Webmaster Mexico
Good point regarding debug 0, but for testing or in your development this does the trick and makes your code easily protable from dev to test to production without any changes.
Comment by teknoid — June 4, 2008 @ 10:10 am
So it does not need any content header like Javascript set in the controller like this?
$this->RequestHandler->setContent(’json’, ‘text/javascript’);
$this->RequestHandler->respondAs(’json’);
Comment by primeminister — June 25, 2008 @ 1:44 pm
@primeminister
Usually you won’t need to set a header. Your JS library should deal with the response correctly (in most cases, at least).
Comment by teknoid — June 25, 2008 @ 4:38 pm