JSON output with CakePHP

Update (2/14/2011): Take a look at a more robust approach that works with recent 1.3 versions of CakePHP.

Update (9/25/2008): Since the writing of this post, the CakePHP manual has been updated with information on using the RequstHandler, which is an excellent supplement to the approach described below. You should definitely familiarize yourself with the way it works:

http://book.cakephp.org/1.2/en/The-Manual/Core-Components/Request-Handling.html

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('recursive' => -1));
  $this->set(compact('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 json_encode($users);
?>

… and really that’s all there is to it.

Related Posts

%d bloggers like this: