Adding JSONP support to older CakePHP versions

Adding JSONP support to older CakePHP versions

When developing VisitorChat, a CakePHP-based live-chat application, I needed to add a plain and simple JSONP-renderer.

At the time, CakePHP did not yet have the JSONP serialiser included, so I went ahead and added JSONP support with a few simple lines of code.

If you are using an older version of CakePHP this may be useful to you. So here we go – just add it to your AppController:

 

1
2
3
4
5
6
7
8
9
10
11
    /**
     * Handles the rendering all jsonp responses
     * @param array $data Array of data to be rendered
     */
    public function __renderJsonp($data = array())
    {
        $this->autoRender = false;
        $this->response->type('js');
        $return = sprintf('%s(%s)', h($this->request->query('callback')), json_encode($data));
        $this->response->body($return);
    }

 

That’s all! Now, you can simply call $this->__renderJsonp(array(‘your’ => ‘data’)); to return your JSONP from within any CakePHP controller action.

No comments

Leave a reply

Your email is never published nor shared. Required fields are marked *

Security Question * Time limit is exhausted. Please reload CAPTCHA.