Question

I'm using django and jquery to implement authenticated sessions and Ajax requests.

I have authenticated session timeouts to log authenticated users out after a long period of inactivity on my site. Some of the pages on my site have a lot of AJAX calls in them that require the user to be in an authenticated session. When a user leaves such a page open for a long time and has the session auto-timed out, any AJAX calls made will just fail and show a browser error. My web stack (django) returns a redirect to login for these AJAX requests, but they just show up as errors to $.ajax() (using jquery.)

How could I reload the page and send the user to the login page through an AJAX request when I find that their auth session has timed out?

Was it helpful?

Solution

One way would be to have a script that just pings a page to see whether or not it's still logged in, but this would increase the number of AJAX requests you'd have to do.

Another option is to have the complete function of $.ajax() check the HTTP status code on the XMLHttpRequest object that is passed in:

$.ajax({..., complete = function(xhr, textStatus){
    if(xhr.status > 300 && xhr.status < 400) //you got a redirect
        window.location.href = '/login/';
    ...
    }, ...);

OTHER TIPS

Simple really, have whatever script you're querying return some sort of error code, maybe

{'error', 'notloggedin'}

then, all you need to do is check for this value in your javascript. If it's found, you then do something like

window.location.href = '/login/';

to make the javascript redirect to the login page (changing the path as necessary)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top