Without ajax, if we load http://example.com/1
and if it redirects to http://example.com/2
then the browser gets appropriate headers and the Browser URL
Well, unfortunately, ajax always follows redirects. However, there is a feature that is not supported in all browsers, you can access the responseURL property of the XMLHttpRequest object.
You can try it in the below code snippet. the redirect button sends ajax request to a URL that replies with 1 redirect (it also works if there are multiple redirects). The no redirect button sends ajax request to a URL with no redirects.
As far as I know this method is not supported in IE 11 and older versions of chrome/firefox/opera browsers.
document.getElementById("no-redirect").addEventListener("click", function() {
testRedirect("https://httpbin.org/get");
});
document.getElementById("redirect").addEventListener("click", function() {
testRedirect("https://httpbin.org/redirect/1");
});
function testRedirect(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(e) {
if (xhr.status == 200 && xhr.readyState == 4) {
if (url != xhr.responseURL) {
alert("redirect detected to: " + xhr.responseURL)
} else {
alert("no redirect detected")
}
}
}
xhr.open("GET", url, true);
xhr.send();
}