What happens if the browser receives a redirect response to an ajax request?
the ajax-request will follow that redirect afaik. The actual content (.responseText, .responseXML) will be the content from the page you are redirected to.
You might be able to intercept the redirect (status-code, location-header) on readyState 2 or 3, but not sure about it.
What happens if the browser receives a redirect response to an ajax request?
Nothing happens. Specifically, the browser doesn't follow the location offered by a redirect response in the same way as it would with a synchronous request. But you can do whatever you like in javascript with the response.
A particular ajax library may handle this case in a specific way, and you should refer to the specific documentation of your Ajax library to see if there is a conventional way for you to deal with this case, such as a callback method for 300-level response codes.
The following illustration fires a raw Ajax to a script which is serving redirect headers. Note the status code of the response as it comes back. It will reflect the HTTP Status Code of the server response.
<html>
<head>
<title>Raw Ajax Request (W3C Model)</title>
</head>
<body>
<script type="text/javascript">
window.onload = function () {
/* Note:
This is a raw example of an Ajax request, following the W3C model.
It should be used for illustration purposes only, and is not a good
example of a robust Ajax communication request.
*/
var xhr = new XMLHttpRequest();
xhr.open("POST", 'http://www.mysite.com/response-test', true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
try {
console.log(xhr.readyState + ':' + xhr.status);
}
catch (e) {
console.log(e);
}
};
xhr.send('{ "responseCode": 302 }');
};
</script>
</body>
</html>
You can emulate these tests yourself with a simple server-side script:
<?php
// Redirect to a location on a different domain.
header ("Location:http://www.stackoverflow.com/");
exit;
?>
Sidenote:
A similar question would be: What happens if an ajax request is redirected?
On the server, the request can be redirected or changed internally. Whatever the server ultimately sends back as a response will serve as your Ajax response. This may or may not include a redirect header.
What happens if the browser receives a redirect response to an ajax request?
If the server sends a redirect (aka a 302 response plus a Location: header) the redirect is automatically followed by the browser. The response to the second request (assuming it also isn't another redirect) is what is exposed to your program.
In fact, you don't have the ability to detect whether a 302 response has occurred. If the 302 redirect leads to a 200, then your program acts identically as if the original request led directly to a 200.
This has been both my experience and the behavior called out in the spec.