Cross domain AJAX querying with jQuery

This post IS NOT about jQuery’s JSONP support. This post is about how to make AJAX queries to domains other then yours. Basically how to achieve cross domain scripting with jQuery. The technique will help you resolve the access to restricted uri denied" code: "1012 problem.

Using this method for cross site scripting you will be able to:
Make AJAX queries to any domain even those that differ from your own;
Use any of $.get(), $.post(), $.ajax(), $getScript(), etc. jQuery AJAX functions as your query method.

But all these does not come free, you will need to put a proxy to between you and the rest of the world. This cross domain querying solution works because you actually loading the content from your own domain. You request the URL and the proxy script on your server actually loading the content from the internet and passing it over to you.
I created a sample PHP proxy that I used to get related news RSS feed for one of my projects.


The PHP script to use as a cross domain scripting proxy:

<?php
// Set your return content type
header('Content-type: application/xml');

// Website url to open
$daurl = 'http://feeds.feedburner.com/jQueryHowto';

// 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);
}
?>
I named the file proxy.php and made my AJAX request to this url. Here is a jQuery code example:

$("#rssFeeds").load("path/to/proxy.php", function(){
// Some callback functions
});
And this is how I overcame the jQuery cross site scripting problems. The bad news is that not all web hosting companies allow fopen() to other domains, but enable it on request. My web server was very strict on security but the script above worked well on it.

If you have better solution, just tell me !

0 comments: