Friday, January 14, 2011

Using JSONP with Grails

This was the scenario; a Grails' controller had to be called using AJAX and then it's result displayed on a PHP page. I knew that jQuery supported JSONP but had no idea how to render a JSONP object in Grails. After hours of frustration and googling around, I finally configured it out. A small sample describing it follows.

Sample Client Program:
$(function(){
$('#searchForm').submit(function(){
var url = 'http://someremotesite.com/search/index?q=test&id=10&callback=?';
$.getJSON(url, null, function(data) {
alert('Result = '+data['result']);
});
return false;
});
});
The most important part is the string "callback=?" added to the end of the URL(see line 3 of program above) makes jQuery to recognise it as a JSONP call. What it basically does is that it supplies the name of the default handler for the AJAX call by storing it in the variable "callback" which we use on the server side.

Sample Server Program:
import grails.converters.JSON

class SearchController {

def index = {

//do some thing

def result = someCalculation()

render "${params.callback}(${result as JSON})"
}
}
The last line(line 11) prints the default assigned callback function along with the JSON data as its parameter. For example, if the default callback function assigned by jQuery is "handleOutput" and jsonData is the "result" object rendered as JSON in above example then Grails renders the output as: handleOutput(jsonData).

The returned JSON object can be manipulated in the same manner as we manipulate any other JSON objects using javascript.

Hope this helps someone out there.

Keep on coding.