2

Using jQuery to perform an ajax POST, as the page requires the user to be authenticated, sometimes (when the session expires), server responds with a 302. So I'm trying to catch that response code from the ajax and redirect to the homepage.

My ajax looks like this:

$.ajax(this.action, {
        type: "POST",
        data: {value:input},
        statusCode: {
            301: function(resp){
                window.location.replace('/');
            },
            302: function(resp){
                window.location.replace('/');
            }
        },
        success: function(response){
            $('#obtained').val(response);
        },
        error: function(error){
            alert(error);
        }
    });

But for some reason the function in the 302 or any other status code never get triggered.

Is this deprecated or am I missing something?

Thanks!

Fede E.
  • 2,118
  • 4
  • 23
  • 39
  • Are you checking if the server is really answering with 3xx statuses in your browser? Your code looks alright – graciano May 11 '18 at 21:49
  • Yes, I checked in the browser and server is returning a 302. I coded the server with node. – Fede E. May 11 '18 at 21:55

1 Answers1

0

Well, apparently the issue is with the 302 redirect. The server does return a 302, however, ajax follows that redirect and finally gets a 200 status code, which causes the function inside the 302 status code to never get fired.

The solution was using some responses in this question: How to manage a redirect request after a jQuery Ajax call

And the final ajax call looks like this:

    $.ajax({
        type: "POST",
        data: {value:input},
        statusCode: {
            301: function(response){
                window.location.reload();
            },
            302: function(response){
                window.location.reload();
            }
        }
    }).done(function(data, statusText, xhr){
        var contentType = xhr.getResponseHeader("Content-Type");
        if (xhr.status === 200 && contentType.toLowerCase().indexOf("text/html") >= 0) { //handles session expiration
            window.location.reload();
        }else{
            $('#obtained').val(data);
        }
    });

Server does return a 302, which ajax follows to the login page, AND as the current code expects a text/plain content type as the "correct" response, it encounters the text/html from the login page, which is what it founds after the redirect, triggering the window.location.reload() to make the actual redirect.

Fede E.
  • 2,118
  • 4
  • 23
  • 39