Cross-domain AJAXCross-domain AJAX

January 28, 2010

When using AJAX, there is a cross-domain security restriction that does not allow accessing an URL with a different domain than the one of the page that contains the script (the script’s domain). For most AJAX applications, this is not an issue, as you can host the data on the same domain. But let’s consider the real case of developing a web page widget. The widget would be a piece of code that any site can put on their pages and the widget should appear there. If that piece of code has to have AJAX functions (like getting search results), you can’t use AJAX because the domain of the script (of the page that includes the script) is the one of the client, and the domain of the data-provider is our server’s domain.
So the solution was to use JSONP (JSON with Padding). JSONP uses the following relaxation of the cross-domain restriction: you can include scripts on your page from another domains. So you can have two scripts on the same page, the scripts having two different domains, and one can call a function from the other one. Of course, calling a function allows exchanging data between those two scripts, so cross-domain communication is possible from JavaScript.
jQuery includes and automates this feature. Here is how you can get JSON data from another domain, using jQuery:

$.getJSON("http://just.another.domain/myscript.php?param="+param+"&callback=?", function(vals) {
	for(var i in vals) {
		// do something with each value
} );

The code for myscript.php could be something like this:

// ... do some processing (based on $_GET['param'])
array_push($results, $val1);
array_push($results, $val2);

echo $_GET['callback'] . '(' . json_encode($results). ');';

jQuery automatically generates a function name and puts it in the place of the second ‘?’, so the function to be called from the PHP-generated JavaScript is available in the ‘callback’ parameter. All that the PHP script has to do is to output a function call using that function name. As a parameter to that function, we put a string with JSON-encoded data. It has to be JSON-encoded, because the parameter is automatically eval’d in the jQuery.
So, with these two restrictions (data has to be packed as JSON and the server script has to output a JavaScript function call), you can transmit data between cross-domain scripts.

Be Sociable, Share!

Leave a Reply