How to manage a redirect request after a jQuery Ajax call How to manage a redirect request after a jQuery Ajax call ajax ajax

How to manage a redirect request after a jQuery Ajax call


I read this question and implemented the approach that has been stated regarding setting the response HTTP status code to 278 in order to avoid the browser transparently handling the redirects. Even though this worked, I was a little dissatisfied as it is a bit of a hack.

After more digging around, I ditched this approach and used JSON. In this case, all responses to AJAX requests have the status code 200 and the body of the response contains a JSON object that is constructed on the server. The JavaScript on the client can then use the JSON object to decide what it needs to do.

I had a similar problem to yours. I perform an AJAX request that has 2 possible responses: one that redirects the browser to a new page and one that replaces an existing HTML form on the current page with a new one. The jQuery code to do this looks something like:

$.ajax({    type: "POST",    url: reqUrl,    data: reqBody,    dataType: "json",    success: function(data, textStatus) {        if (data.redirect) {            // data.redirect contains the string URL to redirect to            window.location.href = data.redirect;        } else {            // data.form contains the HTML for the replacement form            $("#myform").replaceWith(data.form);        }    }});

The JSON object "data" is constructed on the server to have 2 members: data.redirect and data.form. I found this approach to be much better.


I solved this issue by:

  1. Adding a custom header to the response:

    public ActionResult Index(){    if (!HttpContext.User.Identity.IsAuthenticated)    {        HttpContext.Response.AddHeader("REQUIRES_AUTH","1");    }    return View();}
  2. Binding a JavaScript function to the ajaxSuccess event and checking to see if the header exists:

    $(document).ajaxSuccess(function(event, request, settings) {    if (request.getResponseHeader('REQUIRES_AUTH') === '1') {       window.location = '/';    }});


No browsers handle 301 and 302 responses correctly. And in fact the standard even says they should handle them "transparently" which is a MASSIVE headache for Ajax Library vendors. In Ra-Ajax we were forced into using HTTP response status code 278 (just some "unused" success code) to handle transparently redirects from the server...

This really annoys me, and if someone here have some "pull" in W3C I would appreciate that you could let W3C know that we really need to handle 301 and 302 codes ourselves...! ;)