To Top

Our Blog

Guru Technologies

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);
    }

1 Comment

  1. ClientEngage December 2, 2013 at 8:19 am - Reply

    In my older apps (before CakePHP suppored JSONP), I am doing this very similarly. In fact, just yesterday I blogged about it here: http://www.clientengage.com/adding-jsonp-support-to-older-cakephp-versions/

    I suppose, the difference is that I implemented it as a separate (App)Controller method which you need to pass your data to. That said, I really like your approach of it working “automagically” – I haven’t thought of that! 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *