How to manage a redirect request after a jQuery Ajax call
ajax, javascript, jquery, redirect
Solution
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)
top.location.href="login.htm";//redirection
else
funct(data);
}
Then, when making the Ajax call we used something like:
$.post("myAjaxHandler",
{
param1: foo,
param2: bar
},
function(data){
cbWrapper(data, myActualCB);
},
"html"
);
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.
Problem
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?
Related problems
- 403 Forbidden vs 401 Unauthorized HTTP responses
- JQuery catch any ajax error
- Session Cookies expiration handling in ASP.NET MVC 3 while using WIF and jquery ajax requests
- use spring security to tell ajax requests where the login page is
- how to overwrite the success function via JQuery ajaxSend event
- How to redirect the user to another page after login using JavaScript Fetch API?