A simple JSON action helper

by Naneau

JSON is my language of choice for communication between JavaScript and server side scripts. It’s lightweight, and it can be interpreted natively in JavaScript. That means that it’s usually the fastest way of getting information from your server to the browser of your users.

The Zend Framework has an excellent utility for encoding things, called Zend_Json. While it’s usage is ridiculously easy, there are some things you should take into consideration. JSON should be served with text/javascript headers, but JavaScript libraries like prototype also recognize the X-JSON header. Prototype will automatically parse the JSON it finds after that header.

In line with DRY and Zend Framework guidelines, I have created a small action helper that will send a JSON encoded response. You can pass it a single parameter with the thing you want encoded, and an optional second parameter if you want the response to be in a X-JSON header. Usage is easy:

1
2
3
4
//in controller context
$var = array('test' => true);
$this->_helper->json($var);
//send response

It is smart enough to call setNoRender() on viewRenderer if you have it enabled, so you don’t have to worry about that either. The only thing you have to do to set it up is add ‘Naneau/Controller/Action/Helper’, to your action helper broker paths:

1
Zend_Controller_Action_HelperBroker::addPath('Naneau/Controller/Action/Helper/', 'Naneau_Controller_Action_Helper');

Download Naneau_Controller_Action_Helper_Json 0.1

P.S.
Thanks to SpotSec who was able to find no less than 3 problems with my code ;)