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);
} |
/**
* 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.
ClientEngage
ClientEngage is a web-developer who specialises in PHP & MySQL based development. He likes structure and clear architecture and, therefore, focuses on development based on MVC frameworks such as CakePHP and the Slim Framework. Moreover, ClientEngage has experience in technologies such as JavaScript, jQuery, KnockoutJS, C# & .NET, WPF, ADO.NET and Entity Framework to name but a few.
Whilst ClientEngage develops applications for a range of clients, the true focus lies on developing solutions that help you build better relationships with your clients, such as VisitorChat, the PHP Live-Chat or the Project Platform.