JSON-P Mystery

What is JSONP?
JSONP stands for ‘JavaScript Object Notation with Padding’.

For e.g.

// JSON: 
    'name' : 'Mark',
    'age' : 33,
    'hobbies' : ['running','cycling','climbing'],
    'temper' : 'moody'

    'name' : 'Mark',
    'age' : 33,
    'hobbies' : ['running','cycling','climbing'],
    'temper' : 'moody'

As you can see, the only difference is that JSONP format requires some type of callback function with the object passed as a parameter whereas regular JSON is just a regular inline JavaScript object (the theory behind JSONP is that the callback name is specified by the requester (within the query string), not by the party which receives the request).

So, imagine you have a ASP.NET MVC Application on one domain (www.microsoft.com) which outputs JSONP like that shown above. Now to invoke that JSON P call in your domain (www.fabrikam.com) you would use the script tag like shown below

<!-- www.fabrikam.com -->
<script type="text/javascript" src="www.microsoft.com/Home/Index"></script>

Home/Action – It is controller action which returns reponse like newPerson({..}).

In the Fabrikam domain Index.html page would have the global function newperson()

function newPerson(o) {

The above code will alert the name of the person defined in the JSONP data

The purpose of JSONP is to overcome the boundaries of the infamous same-domain-policy which restricts XHR requests to the same domain meaning that you cannot make Ajax requests to other domains. There’s no need to worry about that with JSONP because it doesn’t even require Ajax to work; all it’s doing is using script tags and callbacks…

Issues with JSONP

  • There is no error handling for JSONP calls. If the dynamic script insertion works, you get called; if not, nothing happens. It just fails silently. For example, you are not able to catch a 404 error from the server. Nor can you cancel or restart the request. You can, however, timeout after waiting a reasonable amount of time
  • It can be quite dangerous if used with untrusted services. Because a JSONP service returns a JSON response wrapped in a function call, which will be executed by the browser, this makes the hosting Web application vulnerable to a variety of attacks. So JSPNP calls should be made to trusted sources
  • You cannot do POST operation using JSONP, only GET is supported

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s