complez
complez

Reputation: 8332

jQuery AJAX - made browser request new location in redirect header

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

Upvotes: 3

Views: 19330

Answers (3)

Pim Jager
Pim Jager

Reputation: 32119

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).

Upvotes: 3

Victor
Victor

Reputation: 9269

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"/>

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).

Upvotes: 3

Stein G. Strindhaug
Stein G. Strindhaug

Reputation: 5119

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.

Upvotes: 0

Related Questions