Cross-Site Ajax: Beyond XMLHttpRequest

Part one: Displaying data taken from another site

The XMLHttpRequest object in the current definition has a limitation, it can not load data asynchronously from another site.

This limitation does not exist in Flash, it is possible to retrieve data from other sites, with a security measure, it is required that the site which contains the data has a list of authorized sites that load the data on it.
But it is possible to bridge this gap, and to exchange data between different sites in a safe mode with Ajax using a server side PHP script.

As a first step we will see how simply read a file on another site, and further we will explain how to send data to another site with the necessary security measures.

The principle

When the purpose is just to read a file, the principle is simple:

It is assumed that the other site contains a text file named cross-ajax-get.txt. We want to display its content in a page of this site.

  1. We use the POST command to launch a PHP script on the site. No data is provided, as a safety precaution it contains in a variable the URL of the file to retrieve on the other site.
    It is recommended not to pass the URL as a parameter, it would be a security hole.
  2. The script uses the PHP file_gets_content() function to read the remote file.
  3. It copies the contents in a file called cross-ajax-get.txt on this site.
    Again it is recommended not to pass name of the file to write as a parameter, it would be a critical security hole.
  4. The local generated file is read with the Ajax GET command and its contents displayed on the page that calls the script.

Note that POST and GET command are chained as explained in the tutorial Interacting with a program on the server.

Preview of scripts code

The JavaScript code:

var xhr = createXHR();
  
var script = "ajax-cross-get.php";
var filename = "ajax-cross-get.txt";	
  	
xhr.onreadystatechange=function()
{ 
	if(xhr.readyState == 4)
	{
		 retrieve(filename);
	}
}; 
xhr.open("POST", script, true);		
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(null); 

The POST method makes it possible to launch a PHP script, which in this case is not sent any data. But when the script (below) is executed, and that the status of the XHR object is 4, the function retrieve is called using the GET method to load the local file cross-ajax-get.txt given as a parameter to the function and generated by the PHP function.

The PHP script

$url = "http://www.site-distant.tld/ajax-cross-get.txt";      
$content = file_get_contents($url);
$nfile = fopen("ajax-cross-get.txt", "w");
if($nfile != false)
{
   fwrite($nfile, $content);
   fclose($nfile);
}	

You must change the contents of the $url variable and provide the domain and the extension of the actual site.

The demo

Second part


© 2008-2012 Xul.fr