Two Methods for Handling Cross-Domain Ajax Calls


Two Methods for Handling Cross-Domain Ajax Calls

Use JSONP with jQuery now, but keep an eye on CORS as the next solution for cross-domain access

For security reasons, browsers tend to unilaterally block any calls being made to URLs outside the domain that served the current page. An Ajax page served from, say, dino.com, isn’t allowed to place any Ajax calls to URLs that are located on a different domain. It should be noted that there are no technical reasons that prevent browsers from opening a socket to an endpoint and sending an HTTP request. If that doesn’t happen, it’s because browsers simply don’t want to make cross-domain calls. To confirm this fact, consider that as a user you can enable cross-domain access at any time. All you need to do is open the Options dialog box of a browser, select the Security tab, and change the settings. Figure 1 shows the dialog box you use with Internet Explorer (IE) to enable cross-domain access.

142169_fig1_dialog_enabling_cross-domain-sm
Figure 1: Dialog box for enabling cross-domain data access in Internet Explorer

As a developer, you can’t just assume that end users will set their browsers to allow cross-domain calls. Another solution must be found and applied. Indeed, a few options exist to solve the cross-domain access puzzle. In this article, I’ll first briefly touch on the current de facto solution, “JSON with padding” (JSONP), then focus on a more futuristic solution that I hope will be available once it’s ratified by the World Wide Web Consortium (W3C).

JSONP: The Current Standard for Cross-Domain Access

Although browsers seem reluctant to make cross-domain Ajax calls, they blissfully place cross-domain requests to scripts, images, and HTML pages. In fact, tags such as <script>, <img>, and <iframe> can serve any content from any source regardless of cross-origin security policies. So in theory, you can conceive of pointing a <script> tag to a remote URL and having it serve some content, even dynamically. The problem is, how would you consume this content? A browser would download any content pointed to by a <script> tag, but there’s no automatic way to process that content by passing it to some function. This is precisely the scenario that JSONP addresses.

JSONP is a convention used by some sites to expose their content in a way that makes it easier for callers to consume data via script, even from an external domain. The trick consists in having the site return some JSON content not as a plain string but wrapped up in a script function call. For example, a JSONP-compliant remote endpoint would return a string like this one:

someFunction(“{…}”);

The name of the wrapper function will be provided by the caller as an additional parameter; all that the endpoint does is to get the regular JSON string it would have returned anyway and wrap up the string as an argument passed to the provided script function. This trick now enables you to use a <script> tag like the following:

<script type=”text/javascript”>someFunction(“{…}”);</script>

As you can see, this code is now executable, and it will actually execute as soon as the response is received. JSONP requires that the endpoint and caller agree on a way to pass the name of the wrapper function. Subsequently, you can’t use JSONP with just any site but only with those that explicitly support it.

Thanks to the support that jQuery provides for it, today JSONP is probably the de facto standard for safe cross-domain data access. Using JSONP is no more risky than downloading a script file from a remote site.

Here’s an example of a call in jQuery that uses JSONP to enable cross-domain data access:

var url = http://server/some/endpoint?callback=?
$.getJSON(url, function() {…});

As you can see, the URL has a query string parameter set to a ? symbol. The name of this parameter must be agreed upon between the caller and server. For example, Flickr — one of the first websites to support JSONP — requires you set it to jsoncallback. The name is arbitrary but must be properly documented to allow others to make calls to your server. Callers should set the JSONP query string parameter to the name of the local function they want to act on the data returned from the remote site. So why is jQuery setting it to a wildcard?

The trick is that the jQuery programming model pushes the use of anonymous functions as callbacks, so it would be natural to pass such a function as an argument to $.getJSON. In between your call and the callback acting on returned data, though, is the JSONP wrapper. By adding a ? wildcard to the URL, you tell jQuery to generate on the fly a script function with an auto-generated name that’s passed to the JSONP server. The body of this auto-generated function will then ultimately call into the specified anonymous function.

Figure 2 contains output from the Fiddler freeware tool showing the traffic generated by the JSONP call in the previous code sample.

142169_fig2_traffic_JSOP_call_jQuery-sm
Figure 2: Traffic for a JSONP call using jQuery

In Figure 2, the name of the temporary jQuery function is “jQuery” followed by a GUID, and (230) is the value returned by the remote server. (For the sample URL tested, this is just a randomly generated number.) You can try out the JSONP call yourself by pointing your Ajax page to http://www.expoware.org/demos/cors/cors/getdatajsonp and using “callback” as the JSONP parameter name.

Cross-Origin Resource Sharing

Although fully functional, the JSONP technique for making a cross-domain call is based on a clever trick. In particular, jQuery uses the trick by creating a <script> tag on the fly and making it point to a mangled version of the URL you provide. In today’s world, being unable to connect to any URL you want from an HTML page is a significant restriction. What could be wrong and risky — some say — in a cross-domain call if the remote site agrees to receive calls from some domains? To prove this concept true and provide a definitive answer to the problem of cross-domain access, the W3C is working on a new specification called Cross-Origin Resource Sharing (CORS).

Per the CORS specification, the caller will send a request by adding an Origin header set to the requesting domain. In case of success — that is, if the request is approved by the remote endpoint — the caller will then receive a response that includes a particular header. The header that denotes success of the request is named Access-Control-Allow-Origin and is set either to * or to the name of the requesting domain.

The CORS specification is much more sophisticated than this explanation might suggest. However, this explanation covers just the most common scenario: when the caller needs to place a simple GET/POST request with no other additional HTTP header, such as Modified. You can refer to the W3C draft for a formal description of standards, or check out the Mozilla Developer Network’s HTTP access control page for a more developer-oriented explanation

Copy from http://www.devproconnections.com/article/aspnet2/ajax-cross-domain-142169

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