Tag Archives: cakephp

Return JSONP with CakePHP

Here’s a nice way to turn on JSONP for CakePHP. JSONP, or JSON with padding, is necessary when you want to include JSON from a site different than the one you’re on.

A good explanation for what JSONP is can be found here: http://stackoverflow.com/questions/2067472/what-is-jsonp-all-about

Just include this code on any CakePHP controller that you will be using with JSONP (or you could put it in the AppController to make it work everywhere in your app but that may add a slight performance hit). It checks to make sure that JSON is being returned before trying to apply the padding. This code overrides the afterFilter() which is the last controller action CakePHP does after doing rendering.

    // This funciton makes so JSONP works
    public function afterFilter() {
      parent::afterFilter();
 
      if (empty($this->request->query['callback']) || $this->response->type() != 'application/json') {
          return;
      }
 
      // jsonp response
      App::uses('Sanitize', 'Utility');
      $callbackFuncName = Sanitize::clean($this->request->query['callback']);
      $out = $this->response->body();
      $out = sprintf("%s(%s)", $callbackFuncName, $out);
      $this->response->body($out);
    }