Keep session alive with Javascript
Do you know the problem of huge forms where the user has to provide a lot of values? Sometimes it takes ages to fill out a form or the user just goes for a coffee or even two, leaves the form opened and comes back after two hours and finishes filling out the form. And then? Yeah then the server normally answers with a login screen because the session has expired.
What can we do about that? It is easy. We just keep the session alive with permanent requests to the server directly from the client. I remember that I used this ages ago but the code snippet was gone so I had to write it again. Here we go.
It's a small piece of code but it can really save lives when it comes to long forms. Especially when your boss was working on it for three hours (you know lunch, coffee break, etc. in the meanwhile) and the data is gone because the session expired. We could set the expiration time to lets say 20 hours but this just minimizes the chance of expiration and is not really needed for each page. Especially such a huge expiration costs server resources and is not really recommended. Just drop this Javascript code into your PHP, ASP.net, JSP, Ruby, etc. pages in order to prevent the expiration of the session.
-
function keepMeAlive(imgName) {
-
myImg = document.getElementById(imgName);
-
if (myImg) myImg.src = myImg.src.replace(/\?.*$/, '?' + Math.random());
-
}
-
window.setInterval("keepMeAlive('keepAliveIMG')", 100000);
and last but not least we have to put an image somewhere into our page which will be reloaded every now and then. In this example the image has to get an ID named 'keepAliveIMG' and the width and height must be set to 0 in order to keep the image invisible to the client.
-
<img id="keepAliveIMG" width="1" height="1" src="http://www.some.url/someimg.gif?" />
This script reloads an image called img.gif every 100 seconds and therefore the session will be kept alive as long as the browser stays opened. The question mark after the image filename is needed because we append a random number on every reload. This mimics a completely new image for the browser and prevents getting it from the cache. Have fun.
Other possible ways to keep the session alive:
- Using an iframe and reloading the page within
- requesting a page directly with HTTPRequest. With this we could get rid of an element (for instance image, iframe) within our markup. on the other hand the code is more...
- asking the secretary for the regularly refresh *g*



(11 votes, average: 3.91 out of 5)
May 20th, 2007 at 8:47 pm
I like the concept of using the image, iframe or request to keep page alive, I however do not agree on the purpose... the reason the session expires is to prevent malicious actions on the form, when your boss goes to lunch and comes back and find that somebody submitted erroneous data on his behalf, it never looks good. See, I dont think the concept of sessions is anywhere else as urgent :)
What would be a great help, is after reloggining, the client-side data is re-published, that maybe solved by saving the data every 100 seconds of no activity, to cookies, or a dummy page on the server (may be XML or JSON format)... the trick would be to find out when the page has gone idle, maybe listening to key presses on the page would be enough (a counter is reset every time there is a click or a key press) ;)
thank you for the topic!
July 3rd, 2007 at 2:36 pm
Hey good work there. Please is there a small piece of session expiry code like that, but this time for session expiry not to keep session alive.
July 3rd, 2007 at 3:08 pm
I dont know what you exactly mean. Do you want to let a session expire using JavaScript? If yes just create a serverside script which abandons the session and call this with an XHR from within JavaScript.
August 1st, 2007 at 3:54 am
This is a nice little javascript. Sometimes it is good to keep a session alive for extended periods, in my case when managing a large emergency incident, like Katrina, units from the field can post updates to the web application that is being viewed by Emergency support teams, hospitals and others alike. Having a session expire during these times would just make the application unusable.
Great Job!
September 19th, 2007 at 7:46 pm
In your HTML you will need to add the ? and parameter at the end of whatever URL you enter for the image source; otherwise, the script will not append different random numbers to the URL each time the script runs.
February 15th, 2008 at 7:22 pm
I tried this and it did not work for me. I use php, session time=24 min. After 24 mins, the session expires as usual. Any hint, thanks!
June 20th, 2008 at 5:09 pm
I have a related question that I just can't seem to solve... I have a PHP script that uses sessions to allow an authenticated visitor to access various pages.
The sessions work EXCEPT on a page where I am running a WHILE statement. When I try to click on another page that requires the session, it thinks the session has ended. There is nothing in the code to end the session (except maybe the while statement).
Does a WHILE statement cause a session to close? The WHILE statement looks like this:
while(list($fname, $lname, $username, $password, $sequence) = mysql_fetch_array($result))
{
echo "stuff here...";
}
Your help is GREATLY appreciated!
Jack
July 17th, 2008 at 11:36 pm
Ok, but you left out the key piece of critical information:
"http://www.some.url/someimg.gif"
should be "http://www.some.url/someimg.gif?" with a question mark.
Why do these web posts always try to solve a problem but never give all the required information, causing neverending confusion?
July 18th, 2008 at 12:46 am
brad thanks a lot for pointing that out ... this is type and noone recognized till now :) thanks!!!
July 18th, 2008 at 2:02 am
Thanks for the correction, Michal. The code (with the question mark) does seem to work well! :)
August 20th, 2008 at 11:39 am
my version of the code.... i like it abit more
function keepMeAlive()
{
if (document.getElementById('keepAliveIMG'))
{
document.getElementById('keepAliveIMG').src = 'http://www.some.url/someimg.gif?x=' + escape(new Date());
}
}
window.setInterval("keepMeAlive()", 60000);
October 9th, 2008 at 3:43 pm
I'm also having problems with keeping sessions alive in PHP, even using this method. The javascript is working properly and is being called frequently. The image itself is in its place. Everything's the way it should be, but it still doesn't work. Any ideas? Anyone?
October 9th, 2008 at 10:18 pm
i had same problem in asp.net, try using ajax to retrieve a page you know keeps the session alive like the main page of the site.