Thursday, 11 July 2013

Cross Domain JSON Requests

Now call me late to the game but I thought I would just briefly cover using JSONP for cross domain XHR's, it's a really useful feature which probably doesn't get as much attention as it should.

We all know the pains in trying to get data via XHR from another domain, it's pretty hard to achieve due to security policies, so the only way of using cross domain scripting is to use the HTML <script> tag to load an external Javascript library with the asynchronous attribute, you've probably seen this used by social connectivity plugins such as Facebook or Twitter widgets.

Introducing JSONP...

JSONP is basically just traditional JSON (JavaScript Object Notation) with a bit of extra 'padding', this padding describes how you want to use the data that's being returned so that its not just loaded without any reference.

For example a normal JSON request might contain such data as...
{ "id": "432", "name": "Essential Javascript", "ISDN": "..." }
Which is great but what can we do with it?
addBook( { "id": "432", "name": "Essential Javascript", "ISDN": "..." } );
 That's more like it!

By loading in this content using a HTML <script> tag we have injected the data into the global namespace and given an instruction on what to do with it.

Now all we need to do is define our function...
function addBook( bookDetails ) { }

Now couple this with an OAuth2 enabled API server and your set for a pretty reliable JavaScript API client.


Fortunately for our convenience this has been available in the jQuery library since version 1.5 where jQuery will automatically register a callback in the global namespace (unless you provide your own) and pass along the callback parameter to your URL which will need to handle that which is pretty darn easy. Full documentation can be found on the jQuery AJAX API page.