views:

133

answers:

2

Hi,

This is the first time ever I'm using AJAX, and I want to do the following on an otherwise static page www.xyz.org/some_site.html:

  • Send a GET request to another url "www.xyz.org/testscript"
  • if response has either status code != 200 or content != 'ok': do nothing
  • else: include sth on the website (i.e. set style="display:block" on an element that previously had "display:none")

I've implemented that successfully using basic AJAX. But:

There is an Apache redirect installed pointing from www.xyz.org/testscript to subdomain.xyz.org/testscript, the URL where the actual testscript lives (as AJAX doesn't support cross-domain calls even to subdomains afaik).

When I call www.xyz.org/testscript I get a 302 status code, and the content says "The document has moved here: subdomain.xyz.org/testscript".

How can I grab the 'final' return value?

I guess/hope any AJAX expert can give me a one-liner to solve that ...

A: 

The answer is, according to the comments above:

It's not possible to achieve what I want to do, as AJAX can't be tricked into following a redirect.

EDIT: I tried to solve it by adding another javascript file at subdomain.xyz.org/another.js and throwing all AJAX code from my static html site into it.

Then, on the static html site, I included this script with an ordinary

<script src="subdomain.xyz.org/another.js">

tag. But that wouldn't work either ... cheated myself: Including the javascript on my static page results in the original problem again (cross-domain calls forbidden).

jellybean
Jellybean, in terms of JavaScript's same-origin policy it is irrelevant which server/domain the included script resides on. The only thing that is important is the domain of the document that includes the script.Therefore, moving your script to "subdomain.xyz.org" makes no difference, because it is still included in a document from www.xyz.org. But David Flanagan says it better than me: "As part of the same-origin security policy, the XMLHttpRequest object can issue HTTP requests only to the server from which the document that uses it was downloaded." Cheers, Tom
Tom Bartel
+3  A: 

AJAX (or XMLHttpRequest to be acurate) won't be tricked by a redirect. To be able to get content from another domain you need to use a proxy on the server. The following is a simple PHP proxy:

if(strpos($_GET['q'], "http://") === 0){
  echo file_get_contents($_GET['q']);
}

use it like this:

xhr.open(GET, "www.xyz.org/proxy.php?q=subdomain.xyz.org/testscript", true);
Marius
Make sure you add security before using this script. Otherwise you will find yourself being used for exciting purposes by spammers.
David Dorward