Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an AJAX request to another server

I have AJAX code where if you 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?

like image 636
santhosh Avatar asked May 17 '10 17:05

santhosh


2 Answers

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.

like image 147
Daniel Vassallo Avatar answered Sep 18 '22 09:09

Daniel Vassallo


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.

like image 44
Justin Ethier Avatar answered Sep 21 '22 09:09

Justin Ethier