Returning redirect as response to XHR request

AjaxHttp

Ajax Problem Overview


What happens if the browser receives a redirect response to an ajax request?

Ajax Solutions


Solution 1 - Ajax

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.

2016 Update: Time has passed, and the good news is that the new fetch() API is spec'd to offer finer-grained control of how redirects are handled, with default behavior similar to XHR. That said, it only works where fetch() is implemented natively. Polyfill versions of fetch()—which are based on XHR—continue to have XHR's limitations. Fortunately, native browser support seems to be rounding out nicely.

Solution 2 - Ajax

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.

Solution 3 - Ajax

TLDR: it's doable with fetch.
More info here: https://github.com/axios/axios/issues/932#issuecomment-515229573

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVasilView Question on Stackoverflow
Solution 1 - AjaxgreimView Answer on Stackoverflow
Solution 2 - AjaxjishiView Answer on Stackoverflow
Solution 3 - AjaxkissuView Answer on Stackoverflow