jQuery Across Domain AJAX Content Loads CodeUnit 16 FEB 2010

While working with jQuery and performing AJAX-driven gets and general content loading, have you ever come across your scripts throwing the following error?

permission denied: jquery xhr.open(type, s.url, s.async);

I annoyingly came across this error for the first time a couple of weeks back and after tracing the error all the way back to the main jQuery library file and reading a bit about the thrown error message in particular, I learned something that makes complete and utter sense:

In order to execute better security, Javascript does not allow for AJAX queries to be directed at a different domain from the one on which the AJAX call was originally made.

Makes complete sense, particularly when you think about all those baddies out there, but horribly inconvenient when you do in fact need to load some data that happens to sit on a different data server to the one you actually use as your main web portal.

So is there a fix to this problem that allows cross domain AJAX loading?

The simple answer is yes – as long as you aren’t averse to essentially creating a mini proxy on your own webserver.

Basically what you do to get around the no cross domain querying rule is to create a script that physically grabs the information from the external domain, to which you then point your AJAX load – in other words your display script is talking to your proxy script (which is perfectly legal), and which is in turn talking to the remote domain – in other words the perfect data chain.

To see what I’m trying to describe in action, take a look at the following:

proxy.php contents:

$diginetcontents = file_get_contents('http://diginet.net/modem_info.php?number=' . stripslashes(trim($_GET['to'])));
echo $diginetcontents;

display.php contents:

$('#panel').text = data;

Breaking the above down, what we have done is create a proxy script in proxy.php which simply grabs what is returned from the page on the diginet.net domain, controlling the input by sending along the GET variable it was passed to the file_get_contents function call. The display.php file would be the one that the user is viewing and this initiates the data get from the diginet.net domain by issuing an AJAX get against our proxy script.

It’s an extra step, but now we have the data we couldn’t previously have gotten using pure jQuery with AJAX.

In other words, tutorial done! ;)

(Note, your web server would need something like file_get_contents or fopen which allows for URL parameters to be enabled for this proxy approach to work.)

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • Sdfg

    Look in to JSONP, which is basically this concept..  There are jQuery addons to do this.