Understanding JSONP

JSONP or JSON with padding is a concept to share data to a page from a different origin. If you are writing a JavaScript code to get data from a domain that is different from where the script was loaded, it is not possible to do so using XMLHttpRequest, unless on the source of the data, CORS is enabled.

CORS is a acronym for Cross Origin Resource Sharing. In order to enable CORS for a server side resource, it should be responded with the following headers:

Access-Control-Allow-Headers
Access-Control-Allow-Origin
Access-Control-Allow-Methods

A sample PHP code would look like this:

header(“Access-Control-Allow-Headers:Access-Control-Allow-Origin, X-Requested-With, Content-Type, Accept”);
header(“Access-Control-Allow-Origin:*”);
header(“Access-Control-Allow-Methods:GET,PUT,POST,DELETE”);

With this done, the originating server has authorized any HTTP client to get access to the resource, even if the request comes from a different domain.

JSONP allows an alternate. Instead of sending data for a given request, pad the data with a JavaScript method call. For example, if the data to be sent is “{num1=100, num2=200}” then the JSONP response should look like “callback({num1=100, num2=200})”. The URL to this resource will be loaded as a JavaScript source file.

<script type=”text/javascript” src=”http://vinod.co/rest/contactsjp.php”></script>

This is equivalent to

<script type=”text/javascript”>
callback([{..}, {..}, {..}, ..]);
</script>

Obviously, if you dont have a function defined with the name “callback”, the above script will fail. All you have to do is to define a function called “callback” that has a single argument to receive the data.

 

Watch the following video for a better understanding.