javascript - jquery ajax post example - How to manage a redirect request after a jQuery Ajax call

jquery ajax get example / javascript / jquery / ajax / redirect

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.

John Slegers



Answer #1

Client side: Bind to the ajax events

$('body').bind('ajaxSuccess',function(event,request,settings){
if (401 == request.status){
    window.location = '/users/login';
}
}).bind('ajaxError',function(event,request,settings){
if (401 == request.status){
    window.location = '/users/login';
}
});