Marketing digital. Making results.

Set up JSON action output in CakePHP 1.3

Working  on setting up the Rest Plugin for CakePHP helped me realize that i wanted to set up JSON output for some of my actions. This way, if you request for example “www.yourapp.com/app/post/view/1.json” in the url, you will be returned the JSON post data. This excellent tutorial here will help you achieve it. The steps are simple:

  • Enabling JSON parsing in your app/config/routes.php: Router::parseExtensions('json');
  • Enable the RequestHandler component in your app_controller.php:  //Only enabling json response parsing for url requested with the .json extension  if ($this->RequestHandler->ext === 'json')  {      $this->RequestHandler->setContent('json', 'application/json');  //Prevent debug output that'll corrupt your json data      Configure::write('debug', 0);  }
  • In your app/layouts folder, create a json folder with the default.ctp (so the file path should be app/layout/json/default.ctp) file with the following content:  < ?php  header("Pragma: no-cache");  header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");  header('Content-Type: application/json');  echo $content_for_layout;  ?>
  • Now for all controller actions that you want the json output enabled for, set the variable  in the viewVars for examples in my PostsController view action, i return the post data I want to view as:  $this->set('post', $this->Post->read(null, $id));
  • Now second, we need to create the json view for this data. I created a "json" folder in my "views/posts" folder and created a "view.ctp" file (views/posts/json/view.ctp) with this content:  <?php      echo $this->Js->object($post);   //Some old posts you will find have this as echo $javascript->object($aPosts); This was done with the old Javascript helper, doing some //might give you trouble as it did for me. use the new JS helper syntax as of 1.3  ?>
  • And that’s it you are home free, json output a go go for your action. Access http://www.yourapp.com/view/1and you will get your regular html output, access http://www.yourapp.com/view/1.json and you will be returned your Json output, to view the Json file in Firefox install the JsonView extension.

Now you will notice that for all json views, we will be re-using the same code, basically just changing the name of the variable to output. This call for a JsonView, and I will post aboutit once i get it implemented correctly.