Keep session alive with Javascript

published on December 14, 2006 by Michal
category: 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.

JAVASCRIPT:
  1. function keepMeAlive(imgName) {
  2.    myImg = document.getElementById(imgName);
  3.    if (myImg) myImg.src = myImg.src.replace(/\?.*$/, '?' + Math.random());
  4. }
  5. 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.

HTML:
  1. <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*
1 Star2 Stars3 Stars4 Stars5 Stars (11 votes, average: 3.91 out of 5)
Loading ... Loading ...

13 Responses to “Keep session alive with Javascript”

  1. Mariam Ayyash says...

    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!

     
  2. issa ajao says...

    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.

     
  3. Michal says...

    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.

     
  4. Denny Munson says...

    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!

     
  5. Kurt Crisman says...

    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.

     
  6. Jane says...

    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!

     
  7. Jack says...

    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

     
  8. Brad says...

    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?

     
  9. Michal says...

    brad thanks a lot for pointing that out ... this is type and noone recognized till now :) thanks!!!

     
  10. Brad says...

    Thanks for the correction, Michal. The code (with the question mark) does seem to work well! :)

     
  11. Jon says...

    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);

     
  12. Jon says...

    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?

     
  13. Legion says...

    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.

     

Leave a Reply


Please surround code with [asp]..[/asp], [javascript]..[/javascript], [php]..[/php], [html]..[/html] to highlight source code within your comments.

Currently highest rated articles on webdevbros: