Gareth Lennox

Keeping a session alive

One of the problems we found with people using our content management system was that, frequently, they would take very long editing a page, causing the session to time out, thereby losing their changes.

We could have written code to catch the timout session, and somehow not lose their changes, but we decided on a different course of action, one that I think is much cleaner.

I made use of some javascript and ajax (aka XMLHttpRequest) to ping the server every five minutes. On the server I wrote a special page that would just refresh the session, when requested.

The code is quite simple, we use the setTimeout javascript method to initiate the ping, and ajax to make the call back to the server.

var timeout = 300000; //5 mins
function pingServer()
{
    http = getHTTPObject();
    http.open("GET", 'http://server/admin/ping/', false);
    http.send(null);
    setTimeout('pingServer()', timeout);
}
setTimeout('pingServer()', timeout);

the setTimeout method takes two arguments, a function name, and a timeout value in milliseconds. The getHTTPObject function, is defined on this blog.

Result? The session timeout of 20 minutes is never hit, as long as the user has their browser open. A much better user experience, I would say!

Comments are closed.