I have a web page with a form. When the user submits the form, I want the server to make the browser redirect to a different page from the form action. Right now, I am doing
HTTP 302 response are consumed silently by XmlHttpRequest implementations (e.g. jQuery's ajax
function). It's a feature.
The way I've solved this in the past is to detect for XmlHttpRequests and issue a "Content-Location" header (rather than a "Location"
header). The most cross-library way of doing this is to check for the "X-Requested-With"
http header in your server-side code (jQuery, Prototype, Mootools among others set this):
if (@$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
header('Content-Location: ' . $redirect_url);
} else {
header('Location: ' . $redirect_url);
}
You still need to special-case your client-side code:
$.ajax({
// ...
complete: function(xhr) {
var redirect_url = xhr.getResponseHeader("Content-Location");
if (redirect_url) {
window.location = redirect_url;
}
}
})