Session keep alive in jQuery style

When you want to keep the session alive when a user is visiting a page without refreshes, there is a technique to make this happen. This is for example useful when you have a survey page with a long list of questions that will take a while to answer completely.

The technique is simple (best solutions mostly are simple). You need to notify the server that the client PC is still browsing the page. All you need is a client side script that sends a Ping message behind the scenes and a server side page that handles that ping request.

First the server side: since the request doesn’t need a GUI, a .NET handler can be used:

 1: using System;
 2: using System.Web;
 3: using System.Web.Services;
 4: using System.Web.SessionState;
 5:  
 6: namespace MvcApplication1.Shared
 7: {
 8:     [WebService(Namespace = "http://tempuri.org/")]
 9:     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 10:     public class KeepSessionAlive : IHttpHandler, IRequiresSessionState
 11:     {
 12:         public void ProcessRequest(HttpContext context)
 13:         {
 14:             context.Session["KeepSessionAlive"] = DateTime.Now;
 15:         }
 16:  
 17:         public bool IsReusable
 18:         {
 19:             get
 20:             {
 21:                 return false;
 22:             }
 23:         }
 24:     }
 25: }

 

2nd: the client side script

 1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
 2:  
 3: <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
 4:     Home Page
 5: </asp:Content>
 6:  
 7: <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
 8:     <script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
 9:     <script language="javascript" type="text/javascript">
 10:         $(function() {
 11:             setInterval(KeepSessionAlive, 10000);
 12:         });
 13:  
 14:         function KeepSessionAlive() {            
 15:             $.post("/KeepSessionAlive.ashx", null, function() {
 16:                 $("#result").append("<p>Session is alive and kicking!<p/>");
 17:             });    
 18:         }    
 19:     </script>
 20:     <h2>Will my session die?</h2>    
 21:     <div id="result"></div>
 22: </asp:Content>

Btw, this is a example from a .NET MVC project, but can easily be a plain .html file.

Have fun,

Comments are closed