How can an Ajax callback understand that a user authentication session has ended?

I use django and jquery to implement authenticated Ajax sessions and requests.

I have authenticated session timeouts for registering authenticated users after a long period of inactivity on my site. On some pages of my site there are many AJAX calls in which the user needs to go through an authenticated session. When a user leaves this page open for a long time and has an automatic session shutdown, any AJAX calls made simply 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 in $ .ajax () (using jquery.)

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

+3
source share
2 answers

One way is to have a script that just pings the page to see if it will still be running, but that will increase the number of AJAX requests that you will need to make.

Another option is complete $.ajax()to check the HTTP status code on the XMLHttpRequest object, which is passed to:

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

Just, really, the script you are requesting the return of some error code, maybe

{'error', 'notloggedin'}

then all you have to do is check this value in your javascript. If it is found, then you will do something like

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

javascript ( )

+1

Source: https://habr.com/ru/post/1706005/


All Articles