views:

69

answers:

3

I have an AJAX sample code from W3Schools, where if U request an AJAX call to remote server the request fails:

function loadXMLDoc() {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
    }
  }

  xmlhttp.open("GET", "http://www.google.com", true);
  xmlhttp.send();
}

What can I do to solve this?

+4  A: 

It looks like you have bumped into the same origin policy. You have to use a relative path instead of your absolute http://www.google.com path.

As one possible workaround, you could set up a very simple reverse proxy (with mod_proxy if you are using Apache). This would allow you to use relative paths in your AJAX request, while the HTTP server would be acting as a proxy to any "remote" location.

The fundamental configuration directive to set up a reverse proxy in mod_proxy is the ProxyPass. You would typically use it as follows:

ProxyPass     /web-services/     http://third-party.com/web-services/

In this case, the browser would be requesting /web-services/service.xml but the server would serve this by acting as a proxy to http://third-party.com/web-services/service.xml.

Another common workaround would be to use JSONP.

Daniel Vassallo
+1  A: 

As a security measure, AJAX does not allow you to make requests to other domains. Cross Domain Ajax: a Quick Summary discusses several ways to work around the problem. The easiest way is to use your server as a proxy to download remote content:

This is one of the most common approaches. Your script calls your server, your server makes the call to the remote server and then returns the result back to the client. There are some definite advantages to this approach: you have more control over the entire lifecycle. You can parse the data from the remote server, do with it what you will before sending it back to the client. If anything fails along the way, you can handle it in your own way. And lastly, you can log all remote calls. WIth that you can track success, failure and popularity.

Justin Ethier
A: 

You can use dynamic script loading. Here is an article that I wrote about it.

Dave
@Dave, I don't want to sound like jerk, but your article is simply a snippet of code from a book. Also, it doesn't detail that the other end specifically needs to support this type of script loading and this doesn't work across the board. -1
Doug Neiner
What do you mean this does not work across the board? Can you give me a scenario? This is the only way to do cross domain "ajax-like" requests, because of the same origin policy...
Dave