tags:

views:

9133

answers:

3

Can jQuery ajax made browser request a new location in redirect header send by server?

A: 

Haven't tried jQuery, and a quick peek at the doc doesn't really tell me what a redirect response is handled as. But in Prototype JS any response code other than 2xx "Success" is a onFailure event, thus a redirect is a failure. You could probably parse the response (somehow) in the error block to see what code it is and get the address, wich you can set the document.location to... But it doesn't sound very safe, or practical.

It's more common to print an error of some kind. Or, if the request requires a logged in user, to assume the session has timed out and redirect to the login page.

Stein G. Strindhaug
A: 

You should parse the code and use Javascript to set the document.location

$.get('page.php', { GETvar : 'redirectUrl' }, function(data, textString){  
 if (textString == "succes") { //Succes!
  document.location = data;
 }
 else{ // failure }
});

If you PHP script returns a valid url this will set the location to that url.

EDIT
You could also use a hidden iFrame like this:
html:

     <iframe src="blank.html" name='hiddenframe' id='hiddenframe' onload='readyLoad()'>

And then use some Javascript like this

var first = true;
function setRedirect (url) {
 hiddenframe.location = url;
}
function readyLoad() {
 if( first == true ) { first = false; return false; }
 else {
 alert( 'ready loading, was redireced too:' + myFrame.location.href );
 //Use new location code
}
}

You should wrap these function into nice little event handlers using jQuerys build in functions for that (they are great).

Pim Jager
server send redirect location in header, and i can't find a way to get header response with jquery ajax
complez
I don't think you can send a redirection header through AJAX. AJAX says that a 2## response code is a succes and all others (like the 3## redirection response code) are failures.
Pim Jager
+2  A: 

jQuery does what it is expected to do: follow redirects automatically and go fetch the final page.

You can go to http://jigsaw.w3.org/HTTP/300/ to test it. Open firebug there and inject jquery in the page by editing the HTMLhead and adding

<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.js"/&gt;

to it. Then go to the console and run

$.get("http://jigsaw.w3.org/HTTP/300/301.html", function(r){
    alert(r);
});

and the alert shows the HTML of the redirected page (which is the same one you are in).

Victor