Search Code Shode

Thursday, July 1, 2010

Automatically Refresh User Session Using jQuery ASP.NET - Behind the Scenes

Incredibly simple script will keep your user's session alive without any worries

Now this is something that may or may not be useful to a lot of people, depending on your situation, you may want the user to elect to refresh their Session or not (like banks usually do); but this is for applications that may have a lot of idle time and users are annoyed with their Sessions dying... considering most users don't know what a Session is, but they know that the application stops working correctly.

It uses jQuery and is incredibly simple, just a few lines of code, and no screen flicker or any annoyance to the user at all; ignorance is bliss.

First I include the following in the code-behind in any page you need to keep refreshed (works on masterpages as well):



protected int timeout;
protected void Page_Load(object sender, EventArgs e)
    // one minute prior to timeout (milliseconds)
    timeout = (Session.Timeout * 60000) - 60000;


Protected timeout As Integer
Protected Sub Page_Load(sender As Object, e As EventArgs)
    ' one minute prior to timeout (milliseconds)
    timeout = (Session.Timeout * 60000) - 60000
End Sub

Then add this jQuery to your script:

aspx or master page:
var to;
    to = setTimeout("TimedOut()",);

function TimedOut()
    $.post( "refresh_session.aspx", null,
        if(data == "success")
            to = setTimeout("TimedOut()", );
Notice that the jQuery calls the $.post() function, where it calls the page refresh_session.aspx. That page does only one thing: Response.Write("success"); so if data comes back and it does not equal 'success' (something went wrong) it then stops the cycle of checking for timeout and shows my 'timeout' div that tells
the user it is not a current session.

infinitely refreshing session...

Yup, it is just that easy. The code-behind gets the Session.Timeout, and subtracts one minute from it, this is when the refresh will be triggered. Inside the script, the setTimeout() call will then wait that amount of time and use the jQuery $.post() to hit the page in in turn refresh the Session; once that is done, it starts the cycle over again, so it should repeat on into infinite. And since this is all done via a jQuery ajax
call, there is no evidence to the user this is even happening, no flicker or popup, nothing.