I use jQuery to make an AJAX POST request to my server, which can return HTTP response with status 302. Then JavaScript just sends GET request to this URL, while I'd like to redirect user to URL in this response. Is this possible?
function doAjaxCall() {
$.ajaxSetup({complete: onRequestCompleted});
$.get(yourUrl,yourData,yourCallback);
}
function onRequestCompleted(xhr,textStatus) {
if (xhr.status == 302) {
location.href = xhr.getResponseHeader("Location");
}
}
I don't think so. The W3C says that HTTP redirects with certain status codes, including 302, must be transparently followed.
As an experiment, I tried doing Ajax requests from various browsers (Firefox 3.5, Chrome, IE8, IE7, IE6) to a server giving a 302 status code, and showing the status in the browser's request object. In every case, it showed up as 200.
The accepted answer does not work for the reasons given. I posted a comment with a link to a question that described a hack to get round the problem of the 302 being transparently handled by the browser:
http://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call
However, it is a bit of a dirty hack and after much digging around I found what I think is a better solution - use JSON. In this case, you can make all responses to ajax requests have the code 200 and, in the body of the response, you add some sort of JSON object which your ajax response handler can then use in the appropriate manner.
Rather than asking the Javascript code to Handle 302, it would be better to return a 500 with custom error code+ message on event of 302