May
11
Make AJAX Call To A Different Domain Using PHP & JQuery
Today I Searched how to make an AJAX call to a URL on a different domain. My first attempt failed with a security error. I dug into the problem a bit and found out that PHP can be used as a proxy to fetch the web content.
AJAX Calls PHP Script On Your Domain -> PHP Script Fetches Content From Remote Domain -> PHP Script Returns The Remote Data Back To The AJAX Call
Below is a sample PHP script that I found and tweaked.
// Set your return content type
header('Content-type: text/html');
// Website url to open
$daurl = 'http://www.otherdomain.com/index.php?sku=' . $_GET["sku"];
// Get that website's content
$handle = fopen($daurl, "r");
// If there is something, read and return
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
Below is the AJAX call to load the content into a div using JQuery
$("#loadremotecontent").load('getprice.php?sku=322000');
The script could be further modified to pass in the entire URL as a parameter so it could be more generic. I would love to hear about other cross domain AJAX options if anyone has any other suggestions.

Instead of further taxing the web server, and if you have control over the output format of the other domain, it’s fairly simple to implement a cross-domain friendly AJAXish behaviour in websites. This requires you to dynamically insert a Javascript import into the head, attach a ‘load’ event to it to dynamically remove that very same import file, and execute a given callback function inside the returned content.
It’d work similar to something like this:
xdomainLoad( url, callbackFunctionName )
{
//create new element
//insert into head
//attach ‘load’ event
//make the script.src = url + “&callback=”+callbackFunctionName;
}
scriptLoadEventFunc( event )
{
//remove element event.target from the head
}
callback( object )
{
//logic here to handle returned content
}
The format of the content would be something like this (it has to be valid JS):
callback( { status:’ok’, data:’blabla’ } );
And presto! X-domain AJAX without proxies!