Cross Domain Requests

In order to generate a rich web experience, it is not uncommon to make requests to servers in other domains. Unfortunately, JavaScript’s same origin policy prohibits you from making a request to a server in another domain. There are many ways to overcome this restriction like, using Jquery’s .ajax method, HTML5 CORS(Cross-Origin Resource Sharing) and JSONP.

JSONP is the simplest way to make a cross domain request. JSONP or “JSON with padding” is a technique that can be used to load JavaScript from a server in a different domain. JSONP takes advantage of the fact that JavaScript’s same origin policy doesn’t apply to the HTML <script> element.

In order to make a call dynamically insert a new <script> tag into your page. The source of that script tag attribute is set to a resource in another domain. This URL includes a callback parameter corresponding to a local JavaScript function. The server in the other domain responds with JavaScript that calls this function, passing JSON as an argument. The client then evaluates this JavaScript, giving it access to the server’s data.

Here is the javascript code that makes the JSONP request.

<html>

<head>

// function to make cross domain call

function loadScript(url)
{
// adding the script tag to the head
var head = document.getElementsByTagName(‘head’)[0];
var script = document.createElement(‘script’);
script.type = ‘text/javascript’;
script.src = url;

// fire the loading
head.appendChild(script);
}

function callbackfn(json){

//handle the json

}

</head>

<body>

<button id=”load” onclick=’loadScript(“url&callback=callbackfn”)’>Deals</button>

</body>

</html>

The following link is an app that is used to get deals around you using jsonp to make the call to an external API.

Jquery’s .ajax() method can be used to make cross domain requests but the app would be much lighter if we use JSONP since we dont have to include the jquery library.

JSONP is only useful if we have to make GET request to the external domain. We can’t use POST as a request method

Advertisements

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