Cross domain AJAX using php

Ajax is not allowed to get data from other domains due to some security reason. Well but sometimes we need to fetch data from other website. this can be done through a proxy. A simple proxy server side scripting can enable to fetch the data from other domains and well that’s your cross domain ajax. here is how the php script look like.

<?php
header('Content-type: text/html');
$url = 'http://www.defaultdomain.com';
if(isset($_GET['proxyUrl'])) {
 $url = $_GET['proxyUrl'];
}
$handle = fopen($url, "r");
if ($handle) {
 while (!feof($handle)) {
 $buffer = fgets($handle, 4096);
 echo $buffer;
 }
 fclose($handle);
}
?>

Well that’s it the proxy server side scripting in php. sorry i dont know other server side scripting languages. Well there is nothing be here. it just opens a url as file and stored in a buffer and echo’s it to the browser. Well now the very important thing is the header function as you can see here the content type is html i.e when the this file is loaded in browser it gives content which is HTML now for ajax if you need to fetch HTML then you can leave it as it is, if you need XML then you have to change the content type to “text/xml”. Now save this php file in your domain as proxy.php so the location of this proxy file is http://yourdomain.com/proxy.php

Now the client side scripting for ajax which is nothing other than javascript. The javascript for regular ajax

function proxyAjax(loadUrl)
{
 var req;
 var url = "proxy.php?proxyUrl=" + loadUrl;
 if (window.XMLHttpRequest)
 {
 req=new XMLHttpRequest();
 }
 else //for ie
 {
 req=new ActiveXObject("Microsoft.XMLHTTP");
 }
 req.onreadystatechange=function()
 {
 if (req.readyState==4 && req.status==200)
 {
 document.getElementById("someDiv").innerHTML=req.responseText;
 }
 }
 req.open("GET",url,true);
 req.send();
}
proxyAjax("http://www.otherdomain.com/");

If you want to request for html and xml content using same php script then you can do it by adding a few lines in client side. When the content type in php is text/html even the xml files are sent to the the client as a html file we have to parse it to xml using DOM parser

<pre>if (window.DOMParser)
 {
 parser=new DOMParser();
 xmlDoc=parser.parseFromString(req.responseText,"text/xml");
 }
else //again for ie
 {
 xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
 xmlDoc.async="false";
 xmlDoc.loadXML(req.responseText);
 }

further reading on dom parsing in w3schools.com

Leave a Reply