Keep session alive with Javascript

By | December 14

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, , JSP, Ruby, etc. pages in order to prevent the expiration of the session.

javascript
< view plain text >
  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.

  1. <img id="keepAliveIMG" width="1" height="1" src="" />

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*

28 comments on “Keep session alive with Javascript

  1. 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. 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. 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. 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. 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. 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. 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. Ok, but you left out the key piece of critical information:

    should be “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. brad thanks a lot for pointing that out … this is type and noone recognized till now :) thanks!!!

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

  11. my version of the code…. i like it abit more

    function keepMeAlive()
    {
    if (document.getElementById(‘keepAliveIMG’))
    {
    document.getElementById(‘keepAliveIMG’).src = ‘ + escape(new Date());
    }
    }
    window.setInterval(“keepMeAlive()”, 60000);

  12. 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. i had same problem in , try using ajax to retrieve a page you know keeps the session alive like the main page of the site.

  14. This concept to live a page is very good. and with this i solved my problem with very efficent way.. thanks i think that it is very uniqe idea … Thanks

  15. One thing to note is that this will not work with IIS/ASP. The session will not be renewed by simply requesting a .gif file. You have to request an asp file. So, a work around is to create a .asp file that binary reads a .gif file and then binary writes that data out to the request with the appropriate http headers.

  16. I also do not think that this would work wiht or PHP on IIS. You would have to use the method that I suggested except the for the file would have to be a aspx file that read the binary image data, and for php it would have to be a php file that does the same.

  17. i also failed with PHP on apache, i tried a .php file and it works
    so i think request a static img file won’t work, is that true?

  18. Session state is a function of the server side scripting engine, not the web server. So, requesting just an image file will not work. The request has to be passed to the server side scripting engine (i.e. ASP, PHP, , Python, etc.).

  19. Hi, I have used your code it works in IE 8 ie : reload the image every time

    it works in local , in IE 8 and Mozilla , but not working in IE 7 .. and also

    if the project is moved to IIS - wwwroot Directory , you code has not work .. ???

  20. How does this work with JSP/J2EE type application?
    In my case i need to set the session alive after every 20mins(it is default session out), I tried to use the above mentioned logic and end up with fail.

    I have the same scenario like user enters data into the form and take rest for a while(may be more than 20min), and when come back and enter more data try to save the doc, it shows the error saying timeout/some session out issue.

    How to make it work without form submit(i.e., without reload) to server.

    Thanks,
    -Jee

  21. @Jee Withmosty platforms you cannot just access an image to reset the session. You need to access a page that will cause the server side scripting engine to reset the service. So, you need to access a JSP file. A way you could do it would be to swap the src of an image element with a JSP file that has a date/time stamp query string (to prevent caching). That JSP file would binary read an image file and write it back to the browser with an image content type header. If you are accessing the server side scripting engine that should reset your session.

  22. Here’s a piece of PHP code, that I use to generate 1x1px jpeg image. You can use it with this Michal’s JS to keep sessions alive in PHP environment.

    $img = imagecreate( 1, 1 );
    header( “Content-type: image/jpeg” );
    imagejpeg($img);
    imagedestroy($img);

  23. Great little snippet just what I was looking for

  24. Hi,

    I don’t have java installed on my pc. I have installed only MS office installed.

    I want the script to be executed. Is there any way i can execute the script?

  25. Hi,
    I have tried this script in my web application, which is running on Websphere server. when i test the upload functionality, whcih is taking more than 60mins, session time out is still happening though i have followed the keepmealive script.
    Kindly help me out.

  26. You need to be sure that accessing the image does in fact register as a request with the session provider (and not just serving as a dumb image through Apache or IIS or whatever), by doing something like Mato says to get the PHP/.net/whatever involved - otherwise you’ll be fetching images on a timer up until your session dies, with no ‘keepalive’ effect.

  27. Thank you Michal, This is a very unique solution to a nagging problem we have - long form timing out. Thank you for the code and the instructions. I’m going to get my techs right on this and start testing conversions, this should greatly improve them. Thanks again!

  28. thanks admin cool article yeahh