How to manage a redirect request after a jQuery Ajax call


I'm using $.post() to call a servlet using Ajax and then using the resulting HTML fragment to replace a div element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the div element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed.

How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?


The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function.

For example, our wrapper function was something like:

function cbWrapper(data, funct){
    if($("#myForm", data).length > 0)

Then, when making the Ajax call we used something like:

        param1: foo,
        param2: bar
           cbWrapper(data, myActualCB);

This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.

Another solution I found (especially useful if you want to set a global behaviour) is to use the $.ajaxsetup() method together with the statusCode property. Like others pointed out, don't use a redirect statuscode (3xx), instead use a 4xx statuscode and handle the redirect client-side.

  statusCode : {
    400 : function () {
      window.location = "/";

Replace 400 with the statuscode you want to handle. Like already mentioned 401 Unauthorized could be a good idea. I use the 400 since it's very unspecific and I can use the 401 for more specific cases (like wrong login credentials). So instead of redirecting directly your backend should return a 4xx error-code when the session timed out and you you handle the redirect client-side. Works perfect for me even with frameworks like backbone.js

By : morten.c

Some might find the below useful:

I wanted clients to be redirected to the login page for any rest-action that is sent without an authorization token. Since all of my rest-actions are Ajax based, I needed a good generic way to redirect to the login page instead of handling the Ajax success function.

This is what I've done:

On any Ajax request my server will return a Json 200 response "NEED TO AUTHENTICATE" (if the client needs to authenticate).

Simple example in Java (server side):

public class AuthenticationFilter implements ContainerRequestFilter {

    private final Logger m_logger = LoggerFactory.getLogger(AuthenticationFilter.class);

    public static final String COOKIE_NAME = "token_cookie"; 

    public void filter(ContainerRequestContext context) throws IOException {        
        // Check if it has a cookie.
        try {
            Map<String, Cookie> cookies = context.getCookies();

            if (!cookies.containsKey(COOKIE_NAME)) {
                m_logger.debug("No cookie set - redirect to login page");
                throw new AuthenticationException();
        catch (AuthenticationException e) {
            context.abortWith(Response.ok("\"NEED TO AUTHENTICATE\"").type("json/application").build());

In my Javascript I've added the following code:

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    var originalSuccess = options.success;

    options.success = function(data) {
        if (data == "NEED TO AUTHENTICATE") {
        else {

And that's about it.

By : Tomer

This video can help you solving your question :)
By: admin