What problem JSONP solves?
Browsers do not allow cross-domain Ajax requests. For example if you try to make Ajax request to http://www.eventsinindia.com/events/14633.js to get event data you will get following error.
In order to get around this security problem you can do any number of things including sending the Ajax request to your server which will get the JSON data from the eventsinindia.com API. Or use iframe. Both of these solutions are implemented and discussed in this article .
However in some cases JSONP solves this problem much more elegantly.
Before we discuss JSONP some basics ?
When the html page is loaded you will get an alert.
What is JSONP?
From the above section it is clear that if by some means we could dynamically create a
Let’s take an example. If you make a call to http://www.eventsinindia.com/events/14633.js you will get JSON data back.
What needs to be done is while making a call to http://www.eventsinindia.com/events/14633.js pass a parameter called
callback . So in this case the full url would look something like this
Remember callback is a special word here. By using callback we are telling API to wrap the response JSON data with a call to function named AddThisDataToPage.
Using JSONP with jQuery
jQuery makes it easy to use JSONP. Look for documentation on how to use JSONP with jquery here .
Callback is not the name everyone uses
Most of the people use
callback as the key word to identify client is asking for JSONP data. However some people use a different keyword. For example flickr uses the keyword
This returns JSON data
In this case callback is being passed but flickr ignores it.
In this case callback is being passed but the name is jsoncallback.
Providing support for JSONP
All the APIs should provide support for JSONP. Enabling JSONP support is easy if you are using Rails 2.3 or any Rack compliant framework. In Rails 2.3 all you need to do is stick this file in lib as jsonp.rb and then add one line to the environment.rb .
That’s it. Now you are providing support of JSONP with the keyword being