Accessing remote file using Ajax
Problem:
You have to access a remote file in some remote server using ajax.
Consider httpObject is the XMLHttpRequest() or ActiveXObject("Microsoft.XMLHTTP") object.
If you try to user httpObject.open(method, url, true) where url would be the remote file url then it doesn't work.
Solution:
You have to pull the data using some server sided scripting language like PHP, Perl, ASP etc. The following example is done using PHP.
Step 1:
Create the javascript file called ajax.js (where you will be using the ajax requests).
function getHTTPObject(){
if (window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest)
return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function ajaxRequest(){
httpObject = getHTTPObject();
try{
httpObject.open("GET", "bridge.php", true);
httpObject.send(null);
}
catch(err){
document.getElementById('desc').innerHTML = err.description;
}
httpObject.onreadystatechange =
function(){
if(httpObject.readyState == 4)
document.getElementById('desc').innerHTML = httpObject.responseText;
};
}
Step2:
Now create another file called index.html (the page from where you will request a file and view it).
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript" src="Ajax.js"></script>
</head>
<body>
<a href="#" onclick="ajaxRequest();">Load URL</a>
<div id="desc">Text Should Appear Here</div>
</body>
</html>
Step 3:
Finally create bridge.php (This file will actually pull the remote file from remote server)
<?php
header('Content-type: application/xhtml+xml');
echo file_get_contents("http://www.ahmedamin.net");
?>
Comments:
I actually used a trick to pull the remote file data using php file_get_contents method and ajax helped to load the file from the local that php file output. Solution is simple and easy. You can use this solution with any other server sided scripting language.

