Skip to content Skip to sidebar Skip to footer

Is It Possible To Get Page Redirect Information Via Ajax?

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 get's updated. Is there a wa

Solution 1:

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");
});


functiontestRedirect(url) {
  var xhr = newXMLHttpRequest();
  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();
}
<buttonid="redirect">
  Redirect
</button><buttonid="no-redirect">
  No Redirect
</button>

Solution 2:

This might not be exactly what you're looking for, but maybe it will help you get a similar effect.

If you are in control of what the page http://api.example.com does, you could change the way it reacts when it gets a call via AJAX.

You could include a variable in your AJAX call, marking it as such a call, and if this variable is present, not redirect to an other page, but include the URL it would redirect to, in the answer.

The data returned in the AJAx call could be a hash, in which one key represents the redirect url.

data = {status => 1, redirect => 'http://ap2.example.com', …}

(Sorry if that is not a valid PHP hash)

Solution 3:

not sure if I understood it, but just tried something, if it is not what you're looking for please notify me to delete the answer.

here we inject this /#/ in the URL so when clicking on links the browser will have a new segment in the URL which represent the parameter that depending on its value you can determine which page to load using the corresponding AJAX call..

JS/jQuery:

var navLinks = $('#nav a'),
    params = [],
    baseURL = '//localhost/test/js-url-parameters-second';

navLinks.each(function(){
    var oldHREF = $(this).attr('href');
    $(this).attr('href', baseURL +'/#/'+ oldHREF);
});

navLinks.on('click', function(){
    checkURL($(this).attr('href'));
});

functioncheckURL(docURL){
    // if /#/ found then we have URL parameters// grabbing the parameters part of the URLif(docURL.indexOf('/#/') > -1){
        docURL = docURL.split('/#/')[1];
        if(docURL != ''){
            // omit the last forward slash if existsif(docURL[docURL.length - 1] == '/'){
                docURL = docURL.substring(0, docURL.length - 1);
            }
            console.log(docURL);
            $('#page-type').text(docURL);
        }
    } else {
        console.log('No URL parameters found');
    }
}

HTML:

<divid="nav"><ahref="home"data-name="Home">Home</a><ahref="about"data-name="About">About</a><ahref="contact"data-name="Contact">Contact</a></div><hr><divid="container">
  this is the <spanid="page-type">Home</span> page
</div>

Solution 4:

As the already mentioned responseURL doesn't have the best browser support yet, there are 2 more alternative for this case that could be used, http request headers and cookies.

The benefit with these is they don't interfere with the content itself, like for example query string keys, hash tags or embedded in the response data.


Request headers

Server side

  • PHP

    $req->addHeader("X-Response-Url", "....");
    
  • ASP

    headers.Add("X-Response-Url", "....");
    

Client side

xhr.onreadystatechange = function(e) {
  if (xhr.status == 200 && xhr.readyState == 4) {

    var resp_url = xhr.getResponseHeader("X-Response-Url");

    if (send_url != resp_url) {
      // redirected
    }

  }
}

Cookies

  • PHP

    setcookie("XResponseUrl", "...");
    
  • ASP

    Response.Cookies("XResponseUrl") = "..."

Client side

xhr.onreadystatechange = function(e) {
  if (xhr.status == 200 && xhr.readyState == 4) {

    var resp_url = getCookie("XResponseUrl");

    if (send_url != resp_url) {
      // redirected
    }

  }
}


functiongetCookie(name) {
  var re = newRegExp(name + "=([^;]+)");
  var value = re.exec(document.cookie);
  return (value != null) ? unescape(value[1]) : null;
}

Solution 5:

Yes, when you request http://api.example.com using Ajax, browser does not redirect. You can get all the response using jQuery like bellow

$.ajax({
    url: "http://api.example.com",
    success: function(data, textStatus, xhr) {
        console.log(xhr.status);
    },
    complete: function(xhr, textStatus) {
        console.log(xhr.status);
    } 
});

Post a Comment for "Is It Possible To Get Page Redirect Information Via Ajax?"