22 December, 2010

Cross domain communication using jQuery

Due to some restrictions added by browsers, communication across cross domains is not possible by simple use of Ajax technology. It can be done though by adding a server-side script like PHP, and CURLing the other domain to get data and then passing it on to our javascript. But this method requires more code and is
not scalable.

A better way is to dynamically add script to the page, whose source points to the service url and get the response (data) in the script. This is what JSONP
(Javascript Object Notation with Padding) does.

JSON is a lightweight data exchange format for exchanging data between browser and server, and jQuery has a native support for JSONP calls beginning with version 1.2. We can load JSON data located at another domain specifying a JSONP callback.

This can be done as:


$.getJSON(domainurl+"&callback=?", function(response) {
alert("Username: " + response.username);
});


In above code jQuery replaces '?' after 'callback=' with a generated function name to call. And on complete the function name is removed.

Despite its ease of use for cross-domain comunication, JSONP has some drawbacks as well. Lets say, if the dynamic script addition does not work then nothing happens, we do not get any errors, it means there is no any error handling support in JSONP.

No comments: