title: Redirect from an AJAX Post
body: <p>I have an AJAX call to my endpoint in my Spring controller.  After verifying the info from the POST, my controller makes a redirect decision, whether to forward the request to the next location, or send them back to a login page.  The response to the post is correct, it's a 302 with the <code>Location</code> header set correctly.  However, when the page makes the redirect call, it makes an OPTIONS call to the URL, then a GET call, which just returns the HTML.  Great, I have the HTML, but the page stays on my JSP page and never goes to the external URL.  How do I manage this?</p>
  
  <p>Sample Java code:</p>
  
  <pre><code>@RequestMapping(value = "/token/{token_code}", method = {RequestMethod.GET})
  public void validateToken(HttpServletRequest servletRequest, HttpServletResponse servletResponse, @PathVariable String token_code) {
    //set some servlet request attributes from incoming packet info
    if(isTokenValid(token_code)) {
         servletRequest.getRequestDispatcher(MyConstants.JSP_DEVICE_INFO).forward(servletRequest, servletResponse);
     }
    else {
       servletRequest.getRequestDispatcher(MyConstants.FAILURE_URL).forward(servletRequest, servletResponse);
    }
  }
  
  @RequestMapping(value = "/token/tokenRedirect", method = {RequestMethod.POST},headers = "content-type=application/json",consumes = {MediaType.APPLICATION_JSON_VALUE})
  public ModelAndView getSession(HttpServletRequest servletRequest,
                                     HttpServletResponse servletResponse,
                                     @RequestBody TokenValidateRequest request)
  {
    boolean isValid = verifyCollectedInfo(request);
    if(isValid) {
        servletResponse.setHeader("Location", request.url());
        servletResponse.setStatus(302);
  
    }
    else {
        servletResponse.setHeader("Location", MyConstants.FAILURE_URL);
        servletResponse.setStatus(302);
    }
  }
  </code></pre>
  
  <p>JSP Ajax call:</p>
  
  <pre><code>   $.ajax({
           headers: {
               'accept': 'application/json',
               'content-type': 'application/json'
           },
           type: "POST",
           url: "tokenRedirect",
           context:document.body,
           contentType:"application/json",
           data:JSON.stringify(TokenValidateObject)
  
       });
  </code></pre>
  
  <p>So when I inspect my network traffic, I see the 302 status is set for the response and the Location header has the URL I want, but it just fetches the HTML for the redirect URL, it doesn't actually switch views</p>