Lithium (LI3) and JSONP « Km0 Blog

Lithium (LI3) and JSONP
- by admin

I’ve recently started using the really awesome Lithium PHP Framework for a new project.  I really like Lithium because of it’s great support of MongoDB and because it was created by the guys who created CakePHP, my other favorite framework.

So for the current project I’m working on, I am making an API.  Like all good API’s, I need it to return it’s result in different formats (json, xml, jsonp, php).   Lithium is great for that because it looks at the requested content-type and will try to return the data in that format automatically.   For example if you have a bit of jQuery code and tell it to ask for JSON, Lithium will return a json encoded object.

Since it does JSON and XML out of the box, I didn’t have to do any extra code for that part of my API.  However, I needed to support JSONP (ie: wrapping the JSON object in a function call).

I hopped on the Lithium IRC Channel on Freenode (#li3) and asked the guys there.  Here’s what I came up with.  It’s a new Media Type handler that listens for “application/javascript” or “text/javascript” content type request.  When using “type” jsonp in the jQuery AJAX calls, that’s what it sets the accepted content type to.

Media::type('jsonp', array('text/javascript','application/javascript'), array(
    'view' => 'lithium\template\View',
    'layout' => false,
    'paths' => array(
        'template' => '{:library}/views/{:type}.php',
        'layout' => '{:library}/views/{:type}.layout.php'
    'conditions' => array('type' => true),
    'encode' => function($data, $handler, &$response) {
        // do something with it
        return $_GET['callback']."(".json_encode($data).")";

You can add that code to your bootstrap.php file or uncomment the call to bootstrap/media.php and stick it in there (make sure you read or comment out the other code in there).

Now in your javascript you can do things like:

	dataType: 'jsonp',
	url: '',
	context: this,
	success: this.loginHandler

Leave a comment

You must be connected to post a comment.