[jquery] Redirect on Ajax Jquery Call

I am newbie to ajax here and I know somebody would have encountered this problem already. I have a legacy app built on Spring MVC, it has a interceptor(filter) that redirects the user to the login page whenever there is no session.

public class SessionCheckerInterceptor extends HandlerInterceptorAdapter {
 public boolean preHandle(HttpServletRequest request,
   HttpServletResponse response, Object handler) throws Exception {
  HttpSession session = request.getSession();

  // check if userInfo exist in session
  User user = (User) session.getAttribute("user");
  if (user == null) {
   response.sendRedirect("login.htm");
   return false;
  }
  return true;
 }
}

For non-xmlhttp request, this works fine.. but when I try to use ajax in my application, everything gets weird, it is not able to redirect to the login page correctly. As check the value of the

xhr.status = 200 textStatus = parseError errorThrown = "Invalid JSON -Markup of my HTML Login Page-

$(document).ready(function(){
        jQuery.ajax({
            type: "GET",
            url: "populateData.htm",
            dataType:"json",
            data:"userId=SampleUser",
            success:function(response){
             //code here
            },
         error: function(xhr, textStatus, errorThrown) {
                alert('Error!  Status = ' + xhr.status);
             }

        });
});

I checked on my firebug that there is a 302 HTTP response but I am not sure how to catch the response and redirect the user to the login page. Any idea here? Thanks.

This question is related to jquery ajax spring-mvc

The answer is


JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page.

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:

$(document).ready(function(){ 
    jQuery.ajax({ 
        type: "GET", 
        url: "populateData.htm", 
        dataType:"json", 
        data:"userId=SampleUser", 
        success:function(response){ 
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        }, 
     error: function(xhr, textStatus, errorThrown) { 
            alert('Error!  Status = ' + xhr.status); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):

//....
        success:function(response){ 
            if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
                window.location.href = 'login.htm'; 
            }
            else {
                // Process the expected results...
            }
        }
//....

Hope that helps.

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.


For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)