Stefano D'Urso
Stefano D'Urso

Reputation: 53

jquery: how to handle a redirect

I have the following scenario: - a simple html page with a form and some "fields" - when the form is submitted it is performed a GET to a specified URL that replies "302" and the url where the user has to be redirected too is in "Location" header - i checked with fiddler and evetything seems correct

The simple html page includes this piece of code:

function doSubmit() {
    var _url = $("#url").val();
    $.ajax({
        url: _url,
        complete: function(xmlHttp) {
            // xmlHttp is a XMLHttpRquest object
            alert(xmlHttp.status);
 }

The problem is that when submitting the request, i receive as statuscode: 0 and i'm not able to retrieve any "Location" header.

UPDATE

I tried using the Fetch API but it seems it doesn't work:

var req = new Request(url, {
    method: 'get',
    redirect: 'manual',
    "Cache-Control": "no-cache"
});
fetch(req).then(function (res) {
    alert(res.status);
}, function (e) {
    alert('error');
});

It always ends into an error.

Upvotes: 0

Views: 4446

Answers (1)

Rafael
Rafael

Reputation: 18522

Standard ajax requests silently follow redirects and there is no way to stop the browser from doing it.

As alternative to ajax, there is a new Fetch API being developed, which allows manual redirect handling. You need to check if the current browser support is enough for your needs.

The problem with fetch API is, that due to security reasons (preventing data leaks), in case of redirect, the response object is filtered and has status 0. So, basically the only information left is the response.type with the value opaqueredirect. Please see spec draft. In other words, you're allowed to block redirects, but don't have access to the information from the redirect response, unless I missed something.

So, it seams that the answer to your questions is - it's not currently possible to implement full manual redirect handling, including reading the redirect URL from the redirect response.

Upvotes: 2

Related Questions