Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I use JQuery to perform a simple AJAX call to a dummy HTTP Handler that does nothing but keeping my Session alive:</p> <pre><code>function setHeartbeat() { setTimeout("heartbeat()", 300000); // every 5 min } function heartbeat() { $.get( "/SessionHeartbeat.ashx", null, function(data) { //$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :) setHeartbeat(); }, "json" ); } </code></pre> <p>Session handler can be as simple as:</p> <pre><code>public class SessionHeartbeatHttpHandler : IHttpHandler, IRequiresSessionState { public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { context.Session["Heartbeat"] = DateTime.Now; } } </code></pre> <p>The key is to add IRequiresSessionState, otherwise Session won't be available (= null). The handler can of course also return a JSON serialized object if some data should be returned to the calling JavaScript.</p> <p>Made available through web.config:</p> <pre><code>&lt;httpHandlers&gt; &lt;add verb="GET,HEAD" path="SessionHeartbeat.ashx" validate="false" type="SessionHeartbeatHttpHandler"/&gt; &lt;/httpHandlers&gt; </code></pre> <hr> <p><strong>added</strong> from <a href="https://stackoverflow.com/users/28004">balexandre</a> on August 14th, 2012</p> <p>I liked so much of this example, that I want to improve with the HTML/CSS and the beat part</p> <p>change this </p> <pre><code>//$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :) </code></pre> <p>into</p> <pre><code>beatHeart(2); // just a little "red flash" in the corner :) </code></pre> <p>and add</p> <pre><code>// beat the heart // 'times' (int): nr of times to beat function beatHeart(times) { var interval = setInterval(function () { $(".heartbeat").fadeIn(500, function () { $(".heartbeat").fadeOut(500); }); }, 1000); // beat every second // after n times, let's clear the interval (adding 100ms of safe gap) setTimeout(function () { clearInterval(interval); }, (1000 * times) + 100); } </code></pre> <p>HTML and CSS</p> <pre><code>&lt;div class="heartbeat"&gt;&amp;hearts;&lt;/div&gt; /* HEARBEAT */ .heartbeat { position: absolute; display: none; margin: 5px; color: red; right: 0; top: 0; } </code></pre> <p>here is a <strong>live example</strong> for only the beating part: <a href="http://jsbin.com/ibagob/1/" rel="noreferrer">http://jsbin.com/ibagob/1/</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload