Saturday, August 18, 2007

Using Ajax across multiple domains

From http://www.whenpenguinsattack.com/2007/08/13/using-ajax-across-multiple-domains/

XMLHttpRequest, the main component behind AJAX, does not automatically work across multiple domains. This means that you cannot make a request to an ovject on a domain that is different from the web page’s domain. There is an easy solution to this issue: apache’s mod_rewrite module.

Example

function getXMLHttpObject() {
if (window.XMLHTTPRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
return null;
}
}

function handleHTTPResponse() {
if (http.readyState == 4) {
results = http.responseText;
}
}

var http = getXMLHttpObject();

http.open("POST"."http://www.yahoo.com/service");
http.onreadystatechange = handleHttpResponse;

The above example will fail with both Firefox and Internet Explorer (unless you are running it on a web page located on the yahoo domain). There are other ways to allow cross site ajax. Within Internet Exporer, the default security settings can be changed or a host can be added to the “trusted hosts” list. Firefox, on the other hand, has a concept called signed scripts. Both of these methods will not work for most websites on the Internet. This is because it would involve every user coming to your site adding your page to their trusted host list.

Apache setup
  1. Install apache with both mod_rewrite and proxy enabled.
  2. Create the following rule: RewriteRule ^/yahoo_proxy http://www.yahoo.com/service [P]

Note: The [P] indicates a pass-through proxy.

Replace the above line: (http.open("POST"."http://www.yahoo.com/service")) with

http.open("POST"."http://your_host/yahoo_proxy") and a connection will be made to the yahoo domains through your apache server while not violating the security restrictions of IE or Firefox.

http://www.whenpenguinsattack.com/2007/08/13/using-ajax-across-multiple-domains/

No comments:

Total Pageviews

Reading List - 05-Mar-23

Talking to #AI may be the most important job skill of this century ( JohnGoodPasture ) Role of account management over the years. It’s a ro...