Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  38] [ 3]  / answers: 1 / hits: 42313  / 14 Years ago, thu, december 16, 2010, 12:00:00

I know that you can't, when using an XMLHttpRequest, intercept a redirect or prevent it, as the browser will transparently follow it, but is it possible to either



A. Determine whether a request redirected, or



B. Determine where it redirected to? (assuming that the response gives no hints)



Example code:



$.post(/my-url-that-redirects/, {}, 
function(response, statusCode, xmlHttpRequest){
//Somehow grab the location it redirected to
}
);


In my case, firebug will first show a POST to the url, then a GET to the redirected url. Can that GET location be captured?


More From » jquery

 Answers
84

1) Use different status code than 301 (2**) (if request by ajax) and handle redirection on client side:



var STATUS = {
REDIRECT: 280
};

$.post('/redirected', {}, function(response, status, request) {
if (status == STATUS.REDIRECT) {
// you need to return the redirect url
location.href = response.redirectUrl;
} else {
$('#content').html(request.responseText);
}
});


2) DO NOT REDIRECT:



I use that in redirect pattern = redirecting after post request (you don't want to allow user to refresh the post request, etc..)



With ajax request, this is not necessary, so when the post request is ajax, I do forward instead (just forward to different controller - depends on your server-side framework, or what you are using...). POST requests are not cached by browsers.



Actually, I don't know what's the reason you need that, so this might not be so useful for you. This is helpful when server returns different responses for ajax requests than common requests, because when browser redirect ajax request, the redirected request is not XMLHttpRequest...



[updated]



You can access headers (of redirected request) like that:



$.post('redirected', {}, function(r, s, req) {
req.getAllResponseHeaders();
req.getResponseHeader('Location');
});


There should be 'Location' header, but it depends on the server, which headers are sent back...


[#94572] Wednesday, December 15, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karyme

Total Points: 545
Total Questions: 102
Total Answers: 120

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
;