jsonp cross domain ajax call

What is JSONP?

Jsonp is basically json formatting with padding. The padding essentially is set by the server side to automatically call the javascript function that is passed in in the default callback function. That is for example if our ajax is as follows:

url: "http://someotherdomainurl/",
dataType: "jsonp",
data: {
search_term: request.term
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.label,
value: item.id

So basically what happens is if you look at the xhr in firebug .Net tab. You’ll notice that there was another parameter that is passed in: callback=jQuery15109518391547238747_1306729731404. So what we need to do is the output that is returned from the serverside script must call that function on return. The following is a PHP version of that:

$data = getDataAsJSON($_GET['id']);
echo $_GET['callback'] . '(' . $data . ');';
// prints: jQuery15109518391547238747_1306729731404({"name" : "Remy", "id" : "10", "blog" : "http://remysharp.com"});

So for those that are programmers can see that, on return the javascript function: jQuery15109518391547238747_1306729731404() is called with the results of the parameter. This is all done in the background for you by jquery. The function jQuery15109518391547238747_1306729731404 is created on document start and killed upon ajax call completetion. The success function is called with the results of the parameter upon completion.


Leave a Reply