<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>jensbits.com &#187; Web development</title>
	<atom:link href="http://www.jensbits.com/category/webdev/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jensbits.com</link>
	<description></description>
	<lastBuildDate>Wed, 21 Jul 2010 03:44:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>ColdFusion Session Timeout with Warning and jQuery Session Refresh</title>
		<link>http://www.jensbits.com/2010/04/18/coldfusion-session-timeout-with-warning-and-session-refresh/</link>
		<comments>http://www.jensbits.com/2010/04/18/coldfusion-session-timeout-with-warning-and-session-refresh/#comments</comments>
		<pubDate>Sun, 18 Apr 2010 19:05:08 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[ColdFusion]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=681</guid>
		<description><![CDATA[There are times when a user needs to sit on a page for a while either to read or fill out a long form. If their visit is controlled by a session timeout, for example a member site, then the session needs to be refreshed without refreshing the page. My previous post on user session [...]


Related posts:<ol><li><a href='http://www.jensbits.com/2009/09/12/session-timeout-warning-with-coldfusion-and-jqueryjs/' rel='bookmark' title='Permanent Link: ColdFusion Example: Session Timeout Warning with jQuery/JS'>ColdFusion Example: Session Timeout Warning with jQuery/JS</a></li>
<li><a href='http://www.jensbits.com/2009/07/29/coldfusion-dropping-losing-or-resetting-session-variables-and-cfidcftoken/' rel='bookmark' title='Permanent Link: ColdFusion Dropping, Losing, or Resetting Session Variables and CFID/CFTOKEN'>ColdFusion Dropping, Losing, or Resetting Session Variables and CFID/CFTOKEN</a></li>
<li><a href='http://www.jensbits.com/2009/10/23/jquery-ajax-and-jquery-post-form-submit-examples-with-coldfusion/' rel='bookmark' title='Permanent Link: jQuery.ajax and jQuery.post Form Submit Examples with ColdFusion'>jQuery.ajax and jQuery.post Form Submit Examples with ColdFusion</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>There are times when a user needs to sit on a page for a while either to read or fill out a long form. If their visit is controlled by a session timeout, for example a member site, then the session needs to be refreshed without refreshing the page. My <a href="/2009/09/12/session-timeout-warning-with-coldfusion-and-jqueryjs/">previous post on user session warning</a> used a page refresh to renew the session. This example will refresh the session with a jquery .post so the browser maintains state. </p>
<p>Much of what happens here is very similar to the previous page reload session refresh so you will see some of the same explanatory text. Changes to the code mainly affect the jquery/javascript since the variables and timers need to be reset without refreshing the page.</p>
<p>Javascript is needed to keep track of the time the user has been sitting on the page. The server does not know how long they have been sitting there. It only knows whether or not a request comes in during a session or after the session has expired and acts accordingly at that time. Too late for a warning.</p>
<h3>Session Defined: Start to Finish</h3>
<p>A session is defined as when a user begins and ends using or visiting a web site. It can be unlimited in length or strictly defined by a timeout period. If the site requires a log in or accesses sensitive data, it should time out after a period of inactivity. They can end a session by logging out or closing the browser.</p>
<p>Inactivity means the user has done nothing, made no requests of the web server, during a specified time. Ajax requests usually do not count. </p>
<h3>Demo</h3>
<p>The session time left is determined by the server, and, if you want to poll the server with an Ajax request, go for it. Javascript is used to keep track of the time left in the session.</p>
<p>The demo uses a simple log in with session timing handled by jquery and javascript. When the session expiration approaches, the user is warned and given an opportunity to restart the session. If the session time limit is reached, the user is prompted to log in again. If they ignore that prompt, the page automatically redirects to the log in form. In the demo this sequence of events takes 40 seconds to complete and is broken down as follows:</p>
<ol>
<li><em>Session timeout:</em> 30 seconds</li>
<li><strong>Timeout warning:</strong> 20 seconds</li>
<li><strong>Session expired warning:</strong> 10 seconds</li>
<li><strong>Redirect to log in page: </strong>10 seconds</li>
</ol>
<h3>Interrupting the User</h3>
<p>The user&#8217;s attention can be diverted away from other open windows to the eminent session expiration by using a javascript alert in place of the jquery dialog box. Personal preference.</p>
<h3>Code Breakdown</h3>
<p>The application.cfc controls the session by creating non-persistent cookies for CFID and CFTOKEN so the session expires when the user&#8217;s browser closes. It also sets the session variable sessionStartTime. The sessionStartTime variable is used to illustrate the fact that the application.cfc function OnSessionStart only fires once. It does not fire every time a session is renewed or restarted.</p>
<p>RequestStartTime is set in the OnRequestStart function to provide a reference for comparison later. See &#8220;Just for Fun&#8221; section below.</p>
<pre class="brush: coldfusion;">
&lt;cfcomponent
    displayname=&quot;Application&quot;
    output=&quot;false&quot;
    hint=&quot;Handle the application.&quot;&gt;

    &lt;!--- Set up the application. ---&gt;
    &lt;cfset THIS.Name = &quot;sessionrefreshtest&quot; /&gt;
    &lt;cfset THIS.ApplicationTimeout = CreateTimeSpan(0,1,0,0) /&gt;
    &lt;!--- CreateTimeSpan(days, hours, minutes, seconds) ---&gt;
    &lt;cfset THIS.SessionTimeout = CreateTimeSpan(0,0,0,30) /&gt;
    &lt;cfset THIS.SessionManagement = true /&gt;
    &lt;cfset THIS.SetClientCookies = false /&gt;

    &lt;cffunction
        name=&quot;OnSessionStart&quot;
        access=&quot;public&quot;
        returntype=&quot;void&quot;
        output=&quot;false&quot;
        hint=&quot;Fires ONLY ONCE when session first created and not when session renewed/restarted.&quot;&gt;       

        &lt;!---set cfid/cftoken as non-persistent cookies so session ends on browser close ---&gt;
        &lt;cfif not IsDefined(&quot;Cookie.CFID&quot;)&gt;
            &lt;cflock scope=&quot;session&quot; type=&quot;readonly&quot; timeout=&quot;5&quot;&gt;
                &lt;cfcookie name=&quot;CFID&quot; value=&quot;#session.CFID#&quot;&gt;
                &lt;cfcookie name=&quot;CFTOKEN&quot; value=&quot;#session.CFTOKEN#&quot;&gt;
                 &lt;cfset session.SessionStartTime = Now() /&gt;
            &lt;/cflock&gt;
        &lt;/cfif&gt;

        &lt;cfreturn /&gt;
    &lt;/cffunction&gt;

    &lt;cffunction
        name=&quot;OnRequestStart&quot;
        access=&quot;public&quot;
        returntype=&quot;boolean&quot;
        output=&quot;true&quot;
        hint=&quot;Fires at first part of page processing.&quot;&gt;

        &lt;!--- Define arguments. ---&gt;
        &lt;cfargument
            name=&quot;TargetPage&quot;
            type=&quot;string&quot;
            required=&quot;true&quot;
            /&gt;

        &lt;cfset session.RequestStartTime = Now() /&gt;

        &lt;cfreturn true /&gt;

    &lt;/cffunction&gt;    

&lt;/cfcomponent&gt;
</pre>
<p>The log in page checks for a query string variable called &#8216;expired&#8217; and, if present, deletes the session loggedin variable. This is there because the code is going to control the expiration of the session eliminating the need to compensate for browser latency. The actual session start time the time the page loads can differ by several seconds. To avoid having to add time to the session or any other fancy guesswork, when the allotted session time has expired according to the javascript timer on the page, they are done &#8211; session over.</p>
<p>If they are logged in, they get bumped to the index page. The rest is the logic that handles the log in form.</p>
<p>Note: I would not recommend handling a log in form this way. This is for demonstration only.</p>
<pre class="brush: coldfusion;">
&lt;cfif isDefined(&quot;url.expired&quot;) AND url.expired&gt;
    &lt;cfset StructDelete(session,&quot;loggedin&quot;) /&gt;
&lt;/cfif&gt;

&lt;cfif isDefined(&quot;form.username&quot;) AND isDefined(&quot;form.pw&quot;) AND form.username EQ &quot;session&quot; AND form.pw EQ &quot;test&quot;&gt;
    &lt;cfset session.loggedin = true /&gt;
&lt;/cfif&gt;

&lt;cfif StructKeyExists(session, &quot;loggedin&quot;) AND session.loggedin&gt;
    &lt;cflocation url=&quot;index.cfm&quot; addToken=&quot;no&quot; /&gt;
&lt;/cfif&gt;
</pre>
<p>Other than the log in form and a message for the user, that&#8217;s all there is to the log in page.</p>
<h3>Handling Session Timeout</h3>
<p>The index page handles the session timeout code. This could be a separate javascript included in every page. The first block simply determines if they are logged in. If they are not, send them to the login page. If they are, load the index page.</p>
<pre class="brush: coldfusion;">
&lt;!---if not logged in, send them to login page, else load the index page---&gt;
&lt;cfif NOT StructKeyExists(session, &quot;loggedin&quot;) OR NOT session.loggedin&gt;
    &lt;cflocation url=&quot;login.cfm&quot; addToken=&quot;no&quot; /&gt;
&lt;cfelse&gt;
 &lt;!---Load the page ---&gt;
&lt;/cfif&gt;
</pre>
<p>Now the time variables are set and the a javascript timer is set to check the session every 10 seconds.<br />
Javascript uses milliseconds so for clarity the time intervals multiply the number of seconds by 1,000. You could put 10000 in for 10 seconds but I think 10*1000 helps me determine that it is 10 seconds quite a bit faster. Do what is comfortable for you.</p>
<p>Also, a flag is set to determine if the warning dialog box has been opened and the countdown has begun.</p>
<pre class="brush: jscript;">
//Your timing variables in number of seconds
//total length of session in seconds
var sessionLength = 30;
//time warning shown (10 = warning box shown 10 seconds before session starts)
var warning = 10;
//time redirect forced (10 = redirect forced 10 seconds after session ends)
var forceRedirect = 10; 

$(document).ready(function() {
	//event to check session time left (times 1000 to convert seconds to milliseconds)
    checkSessionTimeEvent = setInterval(&quot;checkSessionTime(requestTime)&quot;,10*1000);
});

//event to check session time variable declaration
var checkSessionTimeEvent = &quot;&quot;;

//time session started
var requestTime = new Date();

//initial set of number of seconds to count down from for countdown ticker (10,9,8,7...you get the idea)
var countdownTime = warning;
//create event to start/stop countdownTicker
var countdownTickerEvent = &quot;&quot;; 

//initially set to false. if true - warning dialog open; countdown underway
var warningStarted = false;

function checkSessionTime(reqTime)
{
	//get time now
	var timeNow = new Date(); 

	//clear any countdownTickerEvents that may be running
	clearInterval(countdownTickerEvent);

	//difference between time now and time session started variable declartion
	var timeDifference = 0;

	//session timeout length
	var timeoutLength = sessionLength*1000;

	//set time for first warning, ten seconds before session expires
	var warningTime = timeoutLength - (warning*1000);

	//force redirect to log in page length (session timeout plus 10 seconds)
	var forceRedirectLength = timeoutLength + (forceRedirect*1000);

	timeDifference = timeNow - reqTime;

     if (timeDifference &gt; warningTime &amp;&amp; warningStarted === false)
        {
            //reset number of seconds to count down from for countdown ticker
			countdownTime = warning;

			//call now for initial dialog box text (time left until session timeout)
            countdownTicker(); 

            //set as interval event to countdown seconds to session timeout
            countdownTickerEvent = setInterval(&quot;countdownTicker()&quot;, 1000);

            $('#dialogWarning').dialog('open');
			warningStarted = true;
        }
    else if (timeDifference &gt; timeoutLength)
    	{
    		//close warning dialog box if open
            if ($('#dialogWarning').dialog('isOpen')) $('#dialogWarning').dialog('close');

            $('#dialogExpired').dialog('open');

        }

     if (timeDifference &gt; forceRedirectLength)
     	{
        	//clear (stop) checksession event
            clearInterval(checkSessionTimeEvent);

            //force relocation
            window.location=&quot;login.cfm?expired=true&quot;;
        }
}
</pre>
<p>The countdownTicker function provides a countdown inside the warning dialog box to prompt the user to act now. It uses a timer that fires every second for a 5,4,3,2,1 effect inside the dialog box.</p>
<pre class="brush: jscript;">
function countdownTicker()
{
	//put countdown time left in dialog box
	$(&quot;span#dialogText-warning&quot;).html(countdownTime);

	//decrement countdownTime
	countdownTime--;
}
</pre>
<p>And, the dialog boxes either allow the user to restart the session or, if they did nothing when the warning popped up, it logs them out by redirecting to the log in page with the expired variable in the query string. Also, it redirects to the log in if they hit the close button on the dialog box rather than the Login button on the dialogExpired dialog box.</p>
<pre class="brush: jscript;">
$(function(){
        // jQuery UI Dialog
        $('#dialogWarning').dialog({
            autoOpen: false,
            width: 400,
            modal: true,
            resizable: false,
            buttons: {
                &quot;Restart Session&quot;: function() {
		   //reset session on server
                  $.post(&quot;restart_session.cfm&quot;);

		   //reset the variables
		   requestTime = new Date();
		   warningStarted = false;
		   countdownTime = warning;

		   //clear current checkSessionTimeEvent and start a new one
		   clearInterval(checkSessionTimeEvent);
		   checkSessionTimeEvent = &quot;&quot;;
		   checkSessionTimeEvent = setInterval(&quot;checkSessionTime(requestTime)&quot;,10*1000);

		    $('#dialogWarning').dialog('close');
                }
            }
        });

        $('#dialogExpired').dialog({
            autoOpen: false,
            width: 400,
            modal: true,
            resizable: false,
            close: function() {
                   window.location=&quot;login.cfm?expired=true&quot;;
            },
            buttons: {
                &quot;Login&quot;: function() {
                    window.location=&quot;login.cfm?expired=true&quot;;
                }
            }
        });
});
</pre>
<p>The &#8220;Restart Session&#8221; button sends a post request to a ColdFusion page that sets a session variable. That act alone refreshes the session.</p>
<pre class="brush: coldfusion;">
&lt;!---Setting the give_me_more_time session variable refreshes the session.---&gt;
&lt;cfset session.give_me_more_time = true /&gt;
&lt;!--- Below is optional. There just so you can see a response from the server in firebug. ---&gt;
&lt;cfoutput&gt;session.RequestStartTime: #session.RequestStartTime# session.loggedin: #session.loggedin#&lt;/cfoutput&gt;
</pre>
<p>The dialog box contents are at the bottom of the page but they could be just about anywhere in the body.</p>
<pre class="brush: xml;">
&lt;!--Dialog box contents--&gt;
&lt;div id=&quot;dialogExpired&quot; title=&quot;Session (Page) Expired!&quot;&gt;&lt;p&gt;&lt;span class=&quot;ui-icon ui-icon-alert&quot; style=&quot;float:left; margin:0 7px 0 0;&quot;&gt;&lt;/span&gt; Your session has expired!&lt;p id=&quot;dialogText-expired&quot;&gt;&lt;/p&gt;&lt;/div&gt;

&lt;div id=&quot;dialogWarning&quot; title=&quot;Session (Page) Expiring!&quot;&gt;&lt;p&gt;&lt;span class=&quot;ui-icon ui-icon-alert&quot; style=&quot;float:left; margin:0 7px 0 0;&quot;&gt;&lt;/span&gt; Your session will expire in &lt;span id=&quot;dialogText-warning&quot;&gt;&lt;/span&gt; seconds!&lt;/div&gt;
</pre>
<h3>Just for Fun</h3>
<p>You can view the response from the restrart_session.cfm in Firebug and compare it to the time on the page from the dumped session vars.<br />
<img src="/images/CFsessionFirebug.gif" alt="session time compare" /></p>
<p>Usual recommended jQuery and CF reading:</p>
<div style="height: 250px;">
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0596159773" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0321647491" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847195121" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=032151548X" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
</div>
<p id="demo"><a href="http://cf-jensbits.com/demos/sessionrefresh/login.cfm" onclick="_gaq.push(['_link', 'http://cf-jensbits.com/demos/sessionrefresh/login.cfm']); return false;"><span>Demo</span></a></p>
<p id="download"><a href="/media/code/sessionrefresh.zip"><span>Download zip of all files</span></a></p>
<p class="donate">If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.</p>

<!-- Begin PayPal Donations by http://wpstorm.net/ -->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post"><div class="paypal-donations"><input type="hidden" name="cmd" value="_donations" /><input type="hidden" name="business" value="jen@jensbits.com" /><input type="hidden" name="return" value="http://www.jensbits.com/thank-you/" /><input type="hidden" name="item_name" value="Help pay hosting. All donations go to hosting fees for this site." /><input type="hidden" name="currency_code" value="USD" /><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online." /><img alt="" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" /></div></form>
<!-- End PayPal Donations -->



<p>Related posts:<ol><li><a href='http://www.jensbits.com/2009/09/12/session-timeout-warning-with-coldfusion-and-jqueryjs/' rel='bookmark' title='Permanent Link: ColdFusion Example: Session Timeout Warning with jQuery/JS'>ColdFusion Example: Session Timeout Warning with jQuery/JS</a></li>
<li><a href='http://www.jensbits.com/2009/07/29/coldfusion-dropping-losing-or-resetting-session-variables-and-cfidcftoken/' rel='bookmark' title='Permanent Link: ColdFusion Dropping, Losing, or Resetting Session Variables and CFID/CFTOKEN'>ColdFusion Dropping, Losing, or Resetting Session Variables and CFID/CFTOKEN</a></li>
<li><a href='http://www.jensbits.com/2009/10/23/jquery-ajax-and-jquery-post-form-submit-examples-with-coldfusion/' rel='bookmark' title='Permanent Link: jQuery.ajax and jQuery.post Form Submit Examples with ColdFusion'>jQuery.ajax and jQuery.post Form Submit Examples with ColdFusion</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2010/04/18/coldfusion-session-timeout-with-warning-and-session-refresh/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>jQuery UI Autocomplete Widget with ASP.NET VB</title>
		<link>http://www.jensbits.com/2010/04/14/jquery-ui-autocomplete-widget-with-asp-net/</link>
		<comments>http://www.jensbits.com/2010/04/14/jquery-ui-autocomplete-widget-with-asp-net/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 01:00:23 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[forms]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=671</guid>
		<description><![CDATA[You might also be interested in the Using jQuery Autocomplete to Populate Another Autocomplete post. As a follow up to the jQuery UI Autocomplete Widget with ColdFusion and the jQuery UI Autocomplete Widget with PHP posts, I did one with ASP.NET (VB.NET) as the backend. I swear this is the last one I&#8217;m doing. I&#8217;m [...]


Related posts:<ol><li><a href='http://www.jensbits.com/2010/05/29/using-jquery-autocomplete-to-populate-another-autocomplete-asp-net-coldfusion-and-php-examples/' rel='bookmark' title='Permanent Link: Using jQuery Autocomplete to Populate Another Autocomplete &#8211; ASP.NET, ColdFusion, and PHP Examples'>Using jQuery Autocomplete to Populate Another Autocomplete &#8211; ASP.NET, ColdFusion, and PHP Examples</a></li>
<li><a href='http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/' rel='bookmark' title='Permanent Link: jQuery UI Autocomplete Widget with PHP and MySQL'>jQuery UI Autocomplete Widget with PHP and MySQL</a></li>
<li><a href='http://www.jensbits.com/2010/03/18/jquery-ui-autocomplete-with-coldfusion/' rel='bookmark' title='Permanent Link: jQuery UI Autocomplete Widget with ColdFusion'>jQuery UI Autocomplete Widget with ColdFusion</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<blockquote><p>You might also be interested in the <a href="/2010/05/29/using-jquery-autocomplete-to-populate-another-autocomplete-asp-net-coldfusion-and-php-examples/">Using jQuery Autocomplete to Populate Another Autocomplete post</a>.</p></blockquote>
<p>As a follow up to the<a href="/2010/03/18/jquery-ui-autocomplete-with-coldfusion/"> jQuery UI Autocomplete Widget with ColdFusion</a> and the  <a href="2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/">jQuery UI Autocomplete Widget with PHP</a>  posts, I did one with ASP.NET (VB.NET) as the backend. I swear this is  the last one I&#8217;m doing. I&#8217;m running out of languages that I work in.</p>
<p>The jQuery UI folks have released an <a href=" http://jqueryui.com/demos/autocomplete/">autocomplete widget</a> that is pretty slick. This example uses the JavaScriptSerializer() function in .NET 3.5. I heard a rumor .NET 4 might make this json encoding with data easier. We&#8217;ll see.<br />
<img src="/images/autocomplete_asp.gif" alt="autocomplete" /><br />
This example will use US states and territories to populate the autocomplete. It will also demonstrate how to fill other fields with data returned from the database. This data can be used to fill a visible text box or a hidden form field. It also demonstrates the basic autocomplete functionality which may be fine for some applications.</p>
<p>Of course, you will need the jQuery core file, the jQuery UI core file, and the jQuery UI style sheet of choice. The style sheet comes from the themes available in the jQuery UI website and can be <a href="http://jqueryui.com/download">downloaded with the core file</a>:</p>
<pre class="brush: xml;">
&lt;link type=&quot;text/css&quot; href=&quot;jquery-ui-1.8rc3.custom.css&quot; rel=&quot;stylesheet&quot; /&gt; 

&lt;script type=&quot;text/javascript&quot; src=&quot;jquery-1.4.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;jquery-ui-1.8rc3.custom.min.js&quot;&gt;&lt;/script&gt;
</pre>
<p>The HTML is straight forward and stripped down for the example:</p>
<pre class="brush: xml;">
&lt;form action=&quot;Default.aspx&quot;  method=&quot;post&quot;&gt;
&lt;fieldset&gt;
&lt;legend&gt;jQuery UI Autocomplete Example - ASP.NET VB Backend&lt;/legend&gt;
&lt;p&gt;Start typing the name of a state or territory of the United States&lt;/p&gt;
&lt;p class=&quot;ui-widget&quot;&gt;&lt;label for=&quot;state&quot;&gt;State (abbreviation in separate field): &lt;/label&gt;
	&lt;input type=&quot;text&quot; id=&quot;state&quot;  name=&quot;state&quot; /&gt; &lt;input readonly=&quot;readonly&quot; type=&quot;text&quot; id=&quot;abbrev&quot; name=&quot;abbrev&quot; maxlength=&quot;2&quot; size=&quot;2&quot;/&gt;&lt;/p&gt;
    &lt;input type=&quot;hidden&quot; id=&quot;state_id&quot; name=&quot;state_id&quot; /&gt;
&lt;p class=&quot;ui-widget&quot;&gt;&lt;label for=&quot;state_abbrev&quot;&gt;State (replaced with abbreviation): &lt;/label&gt;
&lt;input type=&quot;text&quot; id=&quot;state_abbrev&quot; name=&quot;state_abbrev&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Submit&quot; /&gt;&lt;/p&gt;
&lt;/fieldset&gt;
&lt;/form&gt;
</pre>
<p>As a bonus, we dump out the form values to see what we have right underneath the form itself:</p>
<pre class="brush: vb;">
Sub Page_Load(Source As Object, E As EventArgs)
 	Dim formfields As String = &quot;&lt;p&gt;&quot; 

     For Each sItem In Request.Form
	 	formfields = formfields + &quot;&lt;strong&gt;&quot; + sItem + &quot;&lt;/strong&gt; = &quot; +  Request.Form(sItem) + &quot;&lt;br /&gt;&quot;
  	Next
	formoutput.Text = formfields + &quot;&lt;/p&gt;&quot;
 End Sub
</pre>
<p>And the jQuery on the page is equally brief:</p>
<pre class="brush: jscript;">
$(function() {

            $('#abbrev').val(&quot;&quot;);

            $(&quot;#state&quot;).autocomplete({
                source: &quot;states.php&quot;,
                minLength: 2,
                select: function(event, ui) {
                    $('#state_id').val(ui.item.id);
                    $('#abbrev').val(ui.item.abbrev);
                }
            });

            $(&quot;#state_abbrev&quot;).autocomplete({
                source: &quot;states_abbrev.php&quot;,
                minLength: 2
            });
        });
</pre>
<p>Notice that there are two autocomplete functions on the page, one for each example in the demo. Each function calls a different aspx file which return slightly different result sets.</p>
<p>Also, the minLength for autocomplete to return results is set to 2 to prevent too many rows from being returned.</p>
<p>Both .NET pages return the data after a few steps:</p>
<ol>
<li>It creates a new javascript serializer</li>
<li>It creates an object to hold the data from each returned row in the query</li>
<li>It queries the database and fills a dataset (keep reading if you like readers better)</li>
<li>Loops an array of the query results adding each row to an object</li>
<li>Adds the object to an ArrayList</li>
<li>Outputs the ArrayList as JSON data</li>
</ol>
<p>The states.aspx file returns the id field, the state field as &#8216;value&#8217;, and the abbrev field. These values are placed in the appropriate text boxes by the autocomplete jQuery function. </p>
<pre class="brush: vb;">
&lt;%@ Page Language=&quot;VB&quot; Debug=&quot;false&quot; %&gt;
&lt;%@ Import Namespace=&quot;System.Web.Script.Serialization&quot; %&gt;
&lt;%@ Import Namespace=&quot;System.Data&quot; %&gt;
&lt;%@ Import Namespace=&quot;System.Data.SqlClient&quot; %&gt;

&lt;script runat=&quot;server&quot;&gt;
    Dim serializer As JavaScriptSerializer

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        serializer = New JavaScriptSerializer()
        Response.Write(JSONData(Request.QueryString(&quot;Term&quot;)))
    End Sub

    Public Class State
        Public id As Integer
        Public value As String
        Public abbrev As String
    End Class

    Private Function JSONData(ByVal term As String) As String

        Dim stateArray As New ArrayList
        Dim index As Integer = 0

        Dim mySql As String
        Dim objConn As New SqlConnection(&quot;YOUR-CONNECTION-STRING-HERE&quot;)
        Dim myds As New DataSet(&quot;States&quot;)
        mySql = &quot;SELECT id, state, abbrev FROM states WHERE state like '%&quot; + term + &quot;%'&quot;

        objConn.Open()

        Dim adapter As New SqlClient.SqlDataAdapter(mySql, objConn)
        adapter.Fill(myds, &quot;States&quot;)
        For Each dr As DataRow In myds.Tables(0).Rows
            Dim st As New State()
            st.id = dr(&quot;id&quot;).ToString()
            st.value = dr(&quot;state&quot;).ToString()
            st.abbrev = dr(&quot;abbrev&quot;).ToString()
            stateArray.Add(st)
        Next

        objConn.Close()

        Return serializer.Serialize(stateArray)
    End Function

    &lt;/script&gt;
</pre>
<p>If you prefer to use a reader, just substitute the code below for the dataset code above.</p>
<pre class="brush: vb;">
        Dim command As New SqlCommand(mySql, objConn)
        Dim reader As SqlDataReader = command.ExecuteReader()

        While reader.Read()
            Dim st As New State()
            st.id = reader(&quot;id&quot;).ToString()
            st.value = reader(&quot;state&quot;).ToString()
            st.abbrev = reader(&quot;abbrev&quot;).ToString()
            stateArray.Add(st)
        End While

        reader.Close()
</pre>
<p>The states_abbrev.aspx shows the basic functionality of the autocomplete function by just assigning results of the query to the &#8216;label&#8217; and &#8216;value&#8217; fields. Explanation on the &#8216;label&#8217; and &#8216;value&#8217; fields from the jQuery UI site:</p>
<p><em>&#8220;The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.&#8221;</em></p>
<pre class="brush: vb;">
&lt;%@ Page Language=&quot;VB&quot; Debug=&quot;false&quot; %&gt;
&lt;%@ Import Namespace=&quot;System.Web.Script.Serialization&quot; %&gt;
&lt;%@ Import Namespace=&quot;System.Data&quot; %&gt;
&lt;%@ Import Namespace=&quot;System.Data.SqlClient&quot; %&gt;

&lt;script runat=&quot;server&quot;&gt;
    Dim serializer As JavaScriptSerializer

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        serializer = New JavaScriptSerializer()
        Response.Write(JSONData(Request.QueryString(&quot;Term&quot;)))
    End Sub

    Public Class State
        Public label As String
        Public value As String
    End Class

    Private Function JSONData(ByVal term As String) As String

        Dim stateArray As New ArrayList
        Dim index As Integer = 0

        Dim mySql As String
        Dim objConn As New SqlConnection(&quot;YOUR-CONNECTION-STRING-HERE&quot;)
        Dim myds As New DataSet(&quot;States&quot;)
        mySql = &quot;SELECT id, state, abbrev FROM states WHERE state like '%&quot; + term + &quot;%'&quot;

        objConn.Open()

        Dim adapter As New SqlClient.SqlDataAdapter(mySql, objConn)
        adapter.Fill(myds, &quot;States&quot;)
        For Each dr As DataRow In myds.Tables(0).Rows
            Dim st As New State()
            st.label = dr(&quot;state&quot;).ToString()
            st.value = dr(&quot;abbrev&quot;).ToString()
            stateArray.Add(st)
        Next

		objConn.Close()

        Return serializer.Serialize(stateArray)
    End Function

    &lt;/script&gt;
</pre>
<p>Again, if you prefer to use a reader, here you go:</p>
<pre class="brush: vb;">
       Dim command As New SqlCommand(mySql, objConn)
        Dim reader As SqlDataReader = command.ExecuteReader()

        While reader.Read()
            Dim st As New State()
            st.label = reader(&quot;state&quot;).ToString()
            st.state = reader(&quot;abbrev&quot;).ToString()
            stateArray.Add(st)
        End While

        reader.Close()
</pre>
<p>Usual recommended jQuery and .NET reading:</p>
<div style="height: 250px;">
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0596159773" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0321647491" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0980576857" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe><br />
</iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0672330113" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe><br />
</iframe></p>
</div>
</div>
<p id="demo"><a href="http://cf-jensbits.com/demos/autocomplete_asp/" onclick="_gaq.push(['_link', 'http://cf-jensbits.com/demos/autocomplete_asp/']); return false;"><span>Demo</span></a></p>
<p class="donate">If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.</p>

<!-- Begin PayPal Donations by http://wpstorm.net/ -->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post"><div class="paypal-donations"><input type="hidden" name="cmd" value="_donations" /><input type="hidden" name="business" value="jen@jensbits.com" /><input type="hidden" name="return" value="http://www.jensbits.com/thank-you/" /><input type="hidden" name="item_name" value="Help pay hosting. All donations go to hosting fees for this site." /><input type="hidden" name="currency_code" value="USD" /><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online." /><img alt="" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" /></div></form>
<!-- End PayPal Donations -->



<p>Related posts:<ol><li><a href='http://www.jensbits.com/2010/05/29/using-jquery-autocomplete-to-populate-another-autocomplete-asp-net-coldfusion-and-php-examples/' rel='bookmark' title='Permanent Link: Using jQuery Autocomplete to Populate Another Autocomplete &#8211; ASP.NET, ColdFusion, and PHP Examples'>Using jQuery Autocomplete to Populate Another Autocomplete &#8211; ASP.NET, ColdFusion, and PHP Examples</a></li>
<li><a href='http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/' rel='bookmark' title='Permanent Link: jQuery UI Autocomplete Widget with PHP and MySQL'>jQuery UI Autocomplete Widget with PHP and MySQL</a></li>
<li><a href='http://www.jensbits.com/2010/03/18/jquery-ui-autocomplete-with-coldfusion/' rel='bookmark' title='Permanent Link: jQuery UI Autocomplete Widget with ColdFusion'>jQuery UI Autocomplete Widget with ColdFusion</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2010/04/14/jquery-ui-autocomplete-widget-with-asp-net/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>CreateUserWizard Set Email as Username VB.NET 3.5</title>
		<link>http://www.jensbits.com/2010/03/05/createuserwizard-set-email-as-username-vb-net-3-5/</link>
		<comments>http://www.jensbits.com/2010/03/05/createuserwizard-set-email-as-username-vb-net-3-5/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 14:00:57 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[Work]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=625</guid>
		<description><![CDATA[Commonly, a login username is the individual&#8217;s email address. If you have used the CreateUserWizard in ASP.NET 3.5, you know that the username field and the email field are separate fields. Username is required by the wizard and email is not. If you want to populate the email field in the database with the username [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>Commonly, a login username is the individual&#8217;s email address. If you have used the CreateUserWizard in ASP.NET 3.5, you know that the username field and the email field are separate fields. Username is required by the wizard and email is not. If you want to populate the email field in the database with the username field, it is not obvious on the surface how to do it. Fortunately, it&#8217;s just some minor mods to the web.config and the aspx page.</p>
<h2>web.config</h2>
<p>In the web.config file, you will add requiresUniqueEmail=&#8221;false&#8221; to the membership provders add entry. Below is a stripped down example.</p>
<pre class="brush: xml;">
 &lt;membership defaultProvider=&quot;MyMembership&quot;&gt;
      &lt;providers&gt;
        &lt;add name=&quot;MyMembership&quot; type=&quot;System.Web.Security.SqlMembershipProvider&quot; connectionStringName=&quot;MyConnectionString&quot; requiresUniqueEmail=&quot;false&quot; /&gt;
        &lt;/providers&gt;
 &lt;/membership&gt;
</pre>
<h2>aspx page</h2>
<p>On the aspx page itself, you will add RequireEmail=&#8221;false&#8221; so the email textbox is not mandatory and a call to a function in the OnCreatedUser event to the CreateUserWizard. Also, some validation is added to the username field to ensure that it is in a valid email format.</p>
<pre class="brush: vb;">
&lt;asp:CreateUserWizard ID=&quot;CreateUserWizard1&quot; OnCreatedUser=&quot;CreateUserWizard1_CreatedUser&quot; RequireEmail=&quot;false&quot; Runat=&quot;server&quot;&gt;

&lt;asp:TextBox ID=&quot;UserName&quot; Width=&quot;200&quot; runat=&quot;server&quot;&gt;&lt;/asp:TextBox&gt;

&lt;asp:RequiredFieldValidator ID=&quot;UserNameRequired&quot; runat=&quot;server&quot; ControlToValidate=&quot;UserName&quot; ErrorMessage=&quot;E-mail is required.&quot;ValidationGroup=&quot;CreateUserWizard1&quot; /&gt;

&lt;asp:RegularExpressionValidator ID=&quot;regEmail&quot; ControlToValidate=&quot;UserName&quot; Text=&quot;Invalid e-mail&quot; ValidationExpression=&quot;\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*&quot; Runat=&quot;server&quot; /&gt;
</pre>
<p>The function fires right after the user is created and updates the email field with the username.</p>
<pre class="brush: vb;">
Protected Sub CreateUserWizard1_CreatedUser(ByVal sender As Object, ByVal e As EventArgs)
        Dim userNameTextBox As TextBox = CType(CreateUserWizardStep1.ContentTemplateContainer.FindControl(&quot;UserName&quot;), TextBox)
        Dim user As MembershipUser = Membership.GetUser(userNameTextBox.Text)

        user.Email = user.UserName
        Membership.UpdateUser(user)
    End Sub
</pre>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2010/03/05/createuserwizard-set-email-as-username-vb-net-3-5/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Google Docs to Create a Survey</title>
		<link>http://www.jensbits.com/2010/02/05/using-google-docs-to-create-a-survey/</link>
		<comments>http://www.jensbits.com/2010/02/05/using-google-docs-to-create-a-survey/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 20:25:15 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[Web development]]></category>
		<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=597</guid>
		<description><![CDATA[After creating the pop-up survey in jQuery, further exploration on creating online polls has turned up Google Docs quick and dirty form creation. Google posted a 2-minute video on Google Docs form creation that pretty much sums it up. This has actually been around for a couple of years now but, even though it&#8217;s a [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>After creating the <a href="/2010/01/29/pop-up-survey-with-jquery-ui-dialog/">pop-up survey in jQuery</a>, further exploration on creating online polls has turned up Google Docs quick and dirty form creation.</p>
<p>Google posted a <a href="http://www.youtube.com/watch?v=IzgaUOW6GIs">2-minute video on Google Docs form creation</a> that pretty much sums it up. This has actually been around for a couple of years now but, even though it&#8217;s a little late to the party, here is a quick illustration of my jQuery poll done with Google Docs:</p>
<p><strong>Select &#8220;Form&#8221; from the &#8220;Create New&#8221; menu.</strong></p>
<p><img src="/images/googleforms/form_01_select.gif" alt="" /></p>
<p><strong>Fill in the name of the poll or form, short description, and the first question.</strong></p>
<p><img src="/images/googleforms/form_02_firstquestion.gif" alt="" /></p>
<p><strong>Add a question by clicking the &#8220;Add Item&#8221; button and choose from the menu items. Under &#8220;More Actions&#8221; you can create the confirmation message and allow the submitters to see the results.</strong> </p>
<p><img src="/images/googleforms/form_03_options.gif" alt="" /></p>
<p><strong>You can also get the embed link for putting the poll right on a web page.</strong> </p>
<p><img src="/images/googleforms/form_04_embed.gif" alt="" /></p>
<p><strong>And, you can email the form and have users submit answers right from their email by hitting the &#8220;Email this form&#8221; button and adding the email addresses.</strong></p>
<p><img src="/images/googleforms/form_05_email.gif" alt="" /></p>
<h2>Here it is in all it&#8217;s embedded goodness. Try it out:</h2>
<p><iframe style="border:1px solid;padding: 5px" src="https://spreadsheets.google.com/embeddedform?formkey=dDNhRVB2el9FTmJpSkR1dEdISDdGRXc6MA" width="500" height="400" frameborder="0" marginheight="0" marginwidth="0">Loading&#8230;</iframe></p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2010/02/05/using-google-docs-to-create-a-survey/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pop-up Survey with jQuery UI Dialog</title>
		<link>http://www.jensbits.com/2010/01/29/pop-up-survey-with-jquery-ui-dialog/</link>
		<comments>http://www.jensbits.com/2010/01/29/pop-up-survey-with-jquery-ui-dialog/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 20:47:23 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[Web development]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=564</guid>
		<description><![CDATA[I was tasked with creating a pop-up survey for a project. Fairly simple whether I used the jQuery dialog or not so I added a &#8220;Thank you&#8221; dialog that displays the survey results with a lightweight, css-based bar chart just for fun. Pop-up Behavior Pop-up survey opens no matter what page of the website the [...]


Related posts:<ol><li><a href='http://www.jensbits.com/2009/12/03/using-jquery-datepicker-and-dialog-box-to-select-date-range/' rel='bookmark' title='Permanent Link: Using jQuery Datepicker and Dialog Box To Select Date Range'>Using jQuery Datepicker and Dialog Box To Select Date Range</a></li>
<li><a href='http://www.jensbits.com/2009/08/10/modal-confirmation-dialog-on-form-submit-javascript-jquery-ui-and-thickbox-varieties/' rel='bookmark' title='Permanent Link: Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties'>Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I was tasked with creating a pop-up survey for a project. Fairly simple whether I used the jQuery dialog or not so I added a &#8220;Thank you&#8221; dialog that displays the survey results with a lightweight, css-based bar chart just for fun.<br />
<img src="/images/survey.gif" alt="pop-up survey" /></p>
<h2>Pop-up Behavior</h3>
<ol>
<li>Pop-up survey opens no matter what page of the website the user enters. </li>
<li>Cookie is set when survey submitted or user opts out (&#8220;No, thanks&#8221; click).</li>
<li>Closing dialog will not set cookie</li>
</ol>
<p>All survey data is stored in a database and jQuery .post is used to shuttle the information back and forth.</p>
<p>Code for the survey dialog:</p>
<pre class="brush: xml;">
&lt;div id=&quot;survey&quot; title=&quot;Pop-Up Survey&quot;&gt;
	&lt;p id=&quot;surveyDenied&quot;&gt;&lt;a href=&quot;#&quot;&gt;No, thanks&lt;/a&gt;&lt;/p&gt;
		&lt;p&gt;Pop-up survey that cookies browser on completion or on opt-out. Short 411 demo survey.&lt;/p&gt;
		&lt;form id=&quot;popup_survey&quot; name=&quot;popup_survey&quot; method=&quot;post&quot;&gt;
        &lt;p&gt;&lt;strong&gt;Pink or blue?&lt;/strong&gt;&lt;br /&gt;
		&lt;input id=&quot;pink&quot; type=&quot;radio&quot; name=&quot;radio_color&quot; value=&quot;pink&quot;  /&gt;Pink&lt;br /&gt;
        &lt;input id=&quot;blue&quot; type=&quot;radio&quot; name=&quot;radio_color&quot; value=&quot;blue&quot;  /&gt;Blue&lt;/p&gt;
        &lt;p&gt;&lt;strong&gt;Soccer or futbol?&lt;/strong&gt;&lt;br /&gt;
		&lt;input id=&quot;soccer&quot; type=&quot;radio&quot; name=&quot;radio_sport&quot; value=&quot;soccer&quot;  /&gt;Soccer&lt;br /&gt;
        &lt;input id=&quot;futbol&quot; type=&quot;radio&quot; name=&quot;radio_sport&quot; value=&quot;futbol&quot;  /&gt;Futbol&lt;/p&gt;
        &lt;/form&gt;
	&lt;div id=&quot;error_message&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>It&#8217;s just a couple of radio buttons and a place for an error message. The submit is handled by the dialog button.</p>
<p>Here is the survey dialog code:</p>
<pre class="brush: jscript;">
$(function(){
			$('#survey').dialog({
				bgiframe: true,
				autoOpen: false,
				modal: true,
				width: 500,
				resizable: false,
				buttons: {
					Submit: function(){
						if($(&quot;input[name='radio_color']:checked&quot;).val() !== undefined &amp;&amp; $(&quot;input[name='radio_sport']:checked&quot;).val() !== undefined){
							setCookie('POPsurvey','POPsurvey',30);
							$.post(&quot;process_survey.php&quot;, $(&quot;#popup_survey&quot;).serialize(),
							function(data){
								if(data.db_check == 'fail'){
									$(&quot;#error_message&quot;).html(&quot;&lt;p&gt;Database not available. Please try again.&lt;/p&gt;&quot;);
								} else {
									$(&quot;div.pink&quot;).css(&quot;width&quot;,data.perPink);
									$(&quot;.perPink&quot;).html(data.perPink + &quot;% (&quot; + data.totalPink + &quot;)&quot;);

									$(&quot;div.blue&quot;).css(&quot;width&quot;,data.perBlue);
									$(&quot;.perBlue&quot;).html(data.perBlue + &quot;% (&quot; + data.totalBlue + &quot;)&quot;);

									$(&quot;div.soccer&quot;).css(&quot;width&quot;,data.perSoccer);
									$(&quot;.perSoccer&quot;).html(data.perSoccer + &quot;% (&quot; + data.totalSoccer + &quot;)&quot;);

									$(&quot;div.futbol&quot;).css(&quot;width&quot;,data.perFutbol);
									$(&quot;.perFutbol&quot;).html(data.perFutbol + &quot;% (&quot; + data.totalFutbol + &quot;)&quot;);

									$(&quot;.totalRes&quot;).html(data.totalRes);

									$('#survey').dialog('close');
									$('#survey_thanks').dialog('open');
								}
								}, &quot;json&quot;);
						}else{
							$(&quot;#error_message&quot;).html(&quot;&lt;p&gt;Please answer all questions.&lt;/p&gt;&quot;);
						}
					}
				}
			});
		});
</pre>
<p>Lots of stuff but it does several things. First, on submit, it checks that the user answered both questions. Then it sets the cookie. And, finally, it sends the form data off via post and puts the response in elements on the page that are part of the &#8220;Thank you&#8221; dialog. Speaking of which&#8230;</p>
<p>The &#8220;Thank you&#8221; dialog code is thus: </p>
<pre class="brush: xml;">
&lt;div id=&quot;survey_thanks&quot; title=&quot;Pop-Up Survey - Thank You!&quot;&gt;
    &lt;p&gt;Thank you for taking the time to answer our survey. Your input will help us improve the site.&lt;/p&gt;
    &lt;p&gt;Responses: &lt;span class=&quot;totalRes&quot;&gt;&lt;/span&gt;&lt;/p&gt;

    &lt;div class=&quot;progress-container&quot;&gt;
        pink &lt;span class=&quot;perPink&quot;&gt;&lt;/span&gt;
        &lt;div class=&quot;pink&quot;&gt;&lt;/div&gt;
        blue &lt;span class=&quot;perBlue&quot;&gt;&lt;/span&gt;
        &lt;div class=&quot;blue&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;

    &lt;div class=&quot;progress-container&quot;&gt;
        soccer &lt;span class=&quot;perSoccer&quot;&gt;&lt;/span&gt;
        &lt;div class=&quot;soccer&quot;&gt;&lt;/div&gt;
        futbol &lt;span class=&quot;perFutbol&quot;&gt;&lt;/span&gt;
        &lt;div class=&quot;futbol&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<pre class="brush: jscript;">
$(function(){
			$('#survey_thanks').dialog({
				bgiframe: true,
				autoOpen: false,
				modal: true,
				width: 500,
				resizable: false,
				buttons: {
					Close: function(){
						$(this).dialog('close');
						}
					}
			});
		});
</pre>
<h2>Processing the Survey</h2>
<p>The process_survey page adds the answers to the database and brings back the totals that are calculated by a view.</p>
<pre class="brush: php;">
$dbhost = 'YOUR_SERVER';
$dbuser = 'YOUR_USERNAME';
$dbpass = 'YOUR_PASSWORD';
$dbname = 'YOUR_DATABASE_NAME';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);

$db_check = 'OK';
$return_arr = array();

if (!$conn)
  {
  $db_check = 'fail';
  }
if ($db_check === 'OK'){
	$insert_sql = mysql_query(&quot;INSERT INTO survey (color,sport) VALUES ('&quot;.$_POST['radio_color'].&quot;','&quot;.$_POST['radio_sport'].&quot;')&quot;);
	if (!$insert_sql) {
		$db_check = 'fail';
	}
}
if ($db_check === 'OK'){
	$fetch = mysql_query(&quot;SELECT * FROM v_totals&quot;);
	/* Retrieve and store in array the results of the query.*/

	while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
		$return_arr[&quot;totalPink&quot;] = $row['Pink'];
		$return_arr[&quot;perPink&quot;] = round($row['Pink']/($row['Pink']+$row['Blue']),2)*100;

		$return_arr[&quot;totalBlue&quot;] = $row['Blue'];
		$return_arr[&quot;perBlue&quot;] = round($row['Blue']/($row['Pink']+$row['Blue']),2)*100;

		$return_arr[&quot;totalFutbol&quot;] = $row['Futbol'];
		$return_arr[&quot;perFutbol&quot;] = round($row['Futbol']/($row['Futbol']+$row['Soccer']),2)*100;

		$return_arr[&quot;totalSoccer&quot;] = $row['Soccer'];
		$return_arr[&quot;perSoccer&quot;] = round($row['Soccer']/($row['Futbol']+$row['Soccer']),2)*100;

		$return_arr[&quot;totalRes&quot;] = $row['Total'];
	}
	/* Retrieve and display the results of the query. */

}
else {
	$db_check = 'fail';
}
/* Free connection resources. */
mysql_close($conn);

$return_arr[&quot;db_check&quot;] = $db_check;

echo json_encode($return_arr);
</pre>
<p>The totals for the return data are stored in a view to prevent separate and multiple calls to the database. The table and the view can be created in MySQL as such:</p>
<pre class="brush: sql;">
CREATE TABLE IF NOT EXISTS `survey` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `color` varchar(4) DEFAULT NULL,
  `sport` varchar(6) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

CREATE VIEW `v_totals` AS select (select count(`survey`.`color`) AS `Expr1` from `survey` where (`survey`.`color` = 'pink')) AS `Pink`,(select count(`survey_2`.`color`) AS `Expr2` from `survey` `survey_2` where (`survey_2`.`color` = 'blue')) AS `Blue`,(select count(`survey_2`.`sport`) AS `Expr3` from `survey` `survey_2` where (`survey_2`.`sport` = 'futbol')) AS `Futbol`,(select count(`survey_2`.`sport`) AS `Expr3` from `survey` `survey_2` where (`survey_2`.`sport` = 'soccer')) AS `Soccer`,(select count(`survey_2`.`id`) AS `Expr4` from `survey` `survey_2`) AS `Total` from `survey` limit 0,1;
</pre>
<h2>Cookies</h2>
<p>The code to handle setting, checking, and deleting cookies is standard javascript:</p>
<pre class="brush: jscript;">
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ &quot;=&quot; +escape(value)+((expiredays==null) ? &quot;&quot; : &quot;;expires=&quot;+exdate.toGMTString());
} 

function getCookie(c_name)
{
	if (document.cookie.length&gt;0)
	  {
	  c_start=document.cookie.indexOf(c_name + &quot;=&quot;);
	  if (c_start!=-1)
		{
		c_start=c_start + c_name.length+1;
		c_end=document.cookie.indexOf(&quot;;&quot;,c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		}
	  }
	return &quot;&quot;;
}

function checkCookie(c_name)
{
	cookie_value=getCookie(c_name);
	if (cookie_value==&quot;&quot;) {
		$('#survey').dialog('open');
	}
}

function deleteCookie(c_name) {
	document.cookie = c_name +'=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}
</pre>
<p>The style for the &#8220;Thank you&#8221; graph:</p>
<pre class="brush: css;">
div.progress-container {
  border: 1px solid #ccc;
  width: 150px;
  padding: 1px;
  margin-bottom: 5px;
  background: white;
}

div.progress-container &gt; div {
  height: 12px;
  margin-bottom: 2px;
}
div.progress-container &gt; div.pink {
  background-color:#CC6699;
}
div.progress-container &gt; div.blue {
  background-color: #3366CC;
}
div.progress-container &gt; div.soccer {
  background-color: #006633;
}
div.progress-container &gt; div.futbol {
  background-color: #663333;
}
</pre>
<p>You&#8217;ll notice in the .post function that the width of the bar graph is set with the percent of responses for each answer that comes back from the database.</p>
<p id="demo"><a href="/demos/survey/"><span>Demo</span></a></p>
<p id="download"><a href="/media/code/jensbits_popup_survey.zip"><span>Download zip of all files</span></a></p>
<p class="donate">If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.</p>

<!-- Begin PayPal Donations by http://wpstorm.net/ -->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post"><div class="paypal-donations"><input type="hidden" name="cmd" value="_donations" /><input type="hidden" name="business" value="jen@jensbits.com" /><input type="hidden" name="return" value="http://www.jensbits.com/thank-you/" /><input type="hidden" name="item_name" value="Help pay hosting. All donations go to hosting fees for this site." /><input type="hidden" name="currency_code" value="USD" /><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online." /><img alt="" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" /></div></form>
<!-- End PayPal Donations -->



<p>Related posts:<ol><li><a href='http://www.jensbits.com/2009/12/03/using-jquery-datepicker-and-dialog-box-to-select-date-range/' rel='bookmark' title='Permanent Link: Using jQuery Datepicker and Dialog Box To Select Date Range'>Using jQuery Datepicker and Dialog Box To Select Date Range</a></li>
<li><a href='http://www.jensbits.com/2009/08/10/modal-confirmation-dialog-on-form-submit-javascript-jquery-ui-and-thickbox-varieties/' rel='bookmark' title='Permanent Link: Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties'>Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2010/01/29/pop-up-survey-with-jquery-ui-dialog/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
		<item>
		<title>Using jQuery Datepicker and Dialog Box To Select Date Range</title>
		<link>http://www.jensbits.com/2009/12/03/using-jquery-datepicker-and-dialog-box-to-select-date-range/</link>
		<comments>http://www.jensbits.com/2009/12/03/using-jquery-datepicker-and-dialog-box-to-select-date-range/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 14:08:11 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[Web development]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=491</guid>
		<description><![CDATA[Using a jquery datepicker in a jquery dialog box to select a date range is a handy, slick way of having users input dates. Date handling and validation in forms when input by the user can be tricky at best. Here a modal dialog box will be used to allow the user to select a [...]


Related posts:<ol><li><a href='http://www.jensbits.com/2010/01/29/pop-up-survey-with-jquery-ui-dialog/' rel='bookmark' title='Permanent Link: Pop-up Survey with jQuery UI Dialog'>Pop-up Survey with jQuery UI Dialog</a></li>
<li><a href='http://www.jensbits.com/2009/08/10/modal-confirmation-dialog-on-form-submit-javascript-jquery-ui-and-thickbox-varieties/' rel='bookmark' title='Permanent Link: Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties'>Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Using a jquery datepicker in a jquery dialog box to select a date range is a handy, slick way of having users input dates. Date handling and validation in forms when input by the user can be tricky at best.</p>
<p>Here a modal dialog box will be used to allow the user to select a date range. That date range will be validated to ensure that it goes from a start date that is prior to the end date. Also, an alternate field will be populated by the datepicker that formats the dates in a specific way. This can be helpful if you are using the dates in a database query or other call that requires a certain format.</p>
<p>First we put a button to open the dialog box and the dialog box itself on the page:</p>
<pre class="brush: xml;">
&lt;button id=&quot;selectDateRange&quot;&gt;Select Date Range&lt;/button&gt;	 

&lt;div id=&quot;dialog&quot; title=&quot;Select Date Range&quot;&gt;
&lt;div id=&quot;message&quot;&gt;&lt;/div&gt;
	&lt;form name=&quot;dateRange&quot; id=&quot;dateRangeForm&quot; action=&quot;index.cfm&quot; method=&quot;post&quot;&gt;
    &lt;label for=&quot;startdate&quot;&gt;Start Date&lt;/label&gt;
    &lt;input id=&quot;startdate&quot; type=&quot;text&quot; readonly /&gt;&lt;input type=&quot;hidden&quot; name=&quot;startdate&quot; 

id=&quot;start_alternate&quot; /&gt;
    &lt;label for=&quot;enddate&quot;&gt;End Date&lt;/label&gt;
    &lt;input id=&quot;enddate&quot; type=&quot;text&quot; readonly /&gt;&lt;input type=&quot;hidden&quot; name=&quot;enddate&quot; id=&quot;end_alternate&quot; 

/&gt;
    &lt;/form&gt;
&lt;/div&gt;
</pre>
<p>A message div is in the dialog box to send the user success or error messages related to their date selection. The input boxes are set to readonly so the user cannot type in a date; they must use the datepicker.</p>
<p>Also needed on the page is a little css to ensure that the datepicker is above the dialog box:</p>
<pre class="brush: xml;">
&lt;style type=&quot;text/css&quot;&gt;
    .ui-datepicker
    {
        z-index: 1003;
    }
&lt;/style&gt;
</pre>
<p>Then the jquery to set the datepicker to the appropriate input box in the dialog box, specify the alternate field and format, and specify min and max dates:</p>
<pre class="brush: jscript;">
$(&quot;#startdate&quot;).datepicker({altField: '#start_alternate',altFormat: 'yy-mm-dd',minDate: '-1y',maxDate: -1});
$(&quot;#enddate&quot;).datepicker({altField: '#end_alternate',altFormat: 'yy-mm-dd',minDate: '-1y',maxDate: -1});
</pre>
<p>The minDate is set to a year from today (user cannot go back more than a year) with &#8216;-1y&#8217; and the maxDate is set to yesterday (user cannot pick today or a future date) with -1. Check the <a href="http://jqueryui.com/demos/datepicker/#option-minDate">jQuery documentation on the datepicker min and maxDates</a> for further explanation.</p>
<p>And, of course, the code for the button that opens our dialog box:</p>
<pre class="brush: jscript;">
$('button#selectDateRange').click(function(){
		$('#dialog').dialog('open');

	});
</pre>
<p>The dialog box code does several things including:</p>
<ul>
<li>Closing the datepicker when the dialog closes</li>
<li>Checking for values in the input boxes</li>
<li>AJAX post to validate the date range</li>
<li>Displaying a message to the user after validating the date range</li>
<li>Sets the additional dialog close button functions</li>
</ul>
<pre class="brush: jscript;">
$(function(){

	// jQuery UI Dialog
	$('#dialog').dialog({
		autoOpen: false,
		width: 400,
		modal: true,
		resizable: false,
		close: function() {
                        $('#message').html('');
			$('#dateRangeForm :input').each(function() {
				$(this).val('');
			});
			$(&quot;#startdate&quot;).datepicker('hide');
			$(&quot;#enddate&quot;).datepicker('hide');
		 },
		buttons: {
			&quot;Submit&quot;: function() {
			var errors = 0;

			$('#dateRangeForm :input').each(function() {
				if($(this).val() == ''){
					$(this).prev().prev().css(&quot;color&quot;, &quot;red&quot;);
					$(this).prev().val('Click box and use calendar to enter date.');
					errors++;
				} else {
					$(this).prev().css(&quot;color&quot;, &quot;black&quot;);
				}
			 });

			if (errors == 0){
				dataString = $('form').serialize();
				$.ajax({
				type: &quot;POST&quot;,
				url: &quot;dateRange.php&quot;,
				data: dataString,
				dataType: &quot;json&quot;,
				success: function(data) {

					if(data == 'invalid'){
						$('#message').html(&quot;&lt;div class='errorMessage'&gt;Date range is invalid.&lt;/div&gt;&quot;);
					} else {
						$('#message').html(&quot;&lt;div class='successMessage'&gt;Date range is valid.&lt;/div&gt;&quot;);
						//location.reload();
					}
				}

			  	});

				return false;

			  }

			  },
				&quot;Close&quot;: function() { 

					$(this).dialog(&quot;close&quot;);
                                        $('#message').html(&quot;&quot;);
			                $('#dateRangeForm :input').each(function() {
				             $(this).val('');
			                });
					$(&quot;#startdate&quot;).datepicker('hide');
					$(&quot;#enddate&quot;).datepicker('hide');
				}
			 }
	});
</pre>
<p>The daterange.php is pretty straightforward:</p>
<pre class="brush: php;">
&lt;?php
	$errormsg = &quot;none&quot;;

	$start_date = new DateTime($_POST[&quot;startdate&quot;]);
	$end_date = new DateTime($_POST[&quot;enddate&quot;]);

	if ($start_date &gt; $end_date)
		$errormsg = &quot;invalid&quot;;

echo json_encode($errormsg);
?&gt;
</pre>
<p>Now, it entirely possible that you can validate the dates without a trip to the server; however, this example sets you up to use the dialog datepicker in more advanced processing or database calls on the server.</p>
<p>Usual recommended jQuery reading:</p>
<div style="height:250px;">
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0596159773" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847196705" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0321647491" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847195121" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
</div>
<p id="demo"><a href="/demos/datepicker/index.php"><span>Demo</span></a></p>
<p id="download"><a href="/media/code/datepicker.zip"><span>Download zip of all files</span></a></p>
<p class="donate">If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.</p>

<!-- Begin PayPal Donations by http://wpstorm.net/ -->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post"><div class="paypal-donations"><input type="hidden" name="cmd" value="_donations" /><input type="hidden" name="business" value="jen@jensbits.com" /><input type="hidden" name="return" value="http://www.jensbits.com/thank-you/" /><input type="hidden" name="item_name" value="Help pay hosting. All donations go to hosting fees for this site." /><input type="hidden" name="currency_code" value="USD" /><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online." /><img alt="" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" /></div></form>
<!-- End PayPal Donations -->



<p>Related posts:<ol><li><a href='http://www.jensbits.com/2010/01/29/pop-up-survey-with-jquery-ui-dialog/' rel='bookmark' title='Permanent Link: Pop-up Survey with jQuery UI Dialog'>Pop-up Survey with jQuery UI Dialog</a></li>
<li><a href='http://www.jensbits.com/2009/08/10/modal-confirmation-dialog-on-form-submit-javascript-jquery-ui-and-thickbox-varieties/' rel='bookmark' title='Permanent Link: Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties'>Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2009/12/03/using-jquery-datepicker-and-dialog-box-to-select-date-range/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Positioning Multiple jQuery UI Dialogs</title>
		<link>http://www.jensbits.com/2009/11/12/positioning-multiple-jquery-ui-dialogs/</link>
		<comments>http://www.jensbits.com/2009/11/12/positioning-multiple-jquery-ui-dialogs/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 01:29:09 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[Web development]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=472</guid>
		<description><![CDATA[This post shows one way to position multiple jQuery UI dialogs on the same page. It positions the dialog over the calling button based on the button&#8217;s position in the viewport. The dialog box contents can be placed anywhere in the body. For this example they look like this: &#60;div id=&#34;helpDialog1&#34; title=&#34;Help &#62;&#62; Dialog 1&#34;&#62; [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>This post shows one way to position multiple <a href="http://jqueryui.com/demos/dialog/">jQuery UI dialogs</a> on the same page. It positions the dialog over the calling button based on the button&#8217;s position in the viewport.</p>
<p>The dialog box contents can be placed anywhere in the body. For this example they look like this:</p>
<pre class="brush: xml;">
&lt;div id=&quot;helpDialog1&quot; title=&quot;Help &gt;&gt; Dialog 1&quot;&gt;
        &lt;p&gt;In id imperdiet justo. Sed eu commodo erat. Nullam euismod dapibus magna a porttitor. Vestibulum odio turpis, ullamcorper eu ullamcorper sit amet, blandit id purus. Suspendisse commodo egestas augue, et fringilla lorem consequat et. Sed volutpat sapien at massa gravida sollicitudin. Nunc ut nibh orci.&lt;/p&gt;
        &lt;p&gt;Nam quis odio vel arcu auctor tincidunt. Aenean vulputate, sapien id porttitor placerat, purus magna viverra ligula, eu tristique justo purus sit amet ligula. Etiam viverra, enim in luctus sollicitudin, arcu nulla accumsan quam, ut mattis orci eros at dui.&lt;/p&gt;

    &lt;p style=&quot;text-align:right;color: #cc0202;&quot;&gt;&lt;a id=&quot;closeHelp1&quot; style=&quot;color:#cc0202;&quot; href=&quot;#&quot;&gt;Close&lt;/a&gt; &lt;strong&gt;X&lt;/strong&gt;&lt;/p&gt;
&lt;/div&gt;

&lt;div id=&quot;helpDialog2&quot; title=&quot;Help &gt;&gt; Dialog 2&quot;&gt;
        &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut aliquam orci eget enim vehicula volutpat. Cras eu tellus quis risus venenatis egestas vitae eget est. Donec nec lorem purus. Duis vitae tortor at lacus placerat rhoncus id sit amet lectus. Suspendisse potenti. Aliquam vitae tortor lorem.&lt;/p&gt;
        &lt;p&gt;Proin ac sem magna. Donec interdum iaculis lacinia. Donec placerat malesuada mi, vitae malesuada sapien tincidunt ut. Mauris a nibh arcu. Etiam a magna a ipsum faucibus sollicitudin. Morbi nisl nunc, porttitor vitae suscipit in, rutrum at augue.&lt;/p&gt;
        &lt;p style=&quot;text-align:right;color:#cc0202;&quot;&gt;&lt;a id=&quot;closeHelp2&quot; style=&quot;color:#cc0202;&quot; href=&quot;#&quot;&gt;Close&lt;/a&gt; &lt;strong&gt;X&lt;/strong&gt;&lt;/p&gt;
&lt;/div&gt;
</pre>
<p>Not much. Just a little styling for sanity&#8217;s sake and lots of Latin. Take note of the id&#8217;s. They are helpDialog1 and helpDialog2. The number will be needed later.</p>
<p>Like, now&#8230;</p>
<pre class="brush: jscript;">
$('[id^=helpDialog]').dialog({
                autoOpen: false,
                modal: false,
                width: 300,
                resizable: false,
                show: 'blind',
                hide: 'blind'
            });
</pre>
<p>The jQuery sets some options for the dialog boxes, and it does this by identifying the dialog boxes with the common part of the id. The &#8216;^&#8217; means &#8216;starts with&#8217; as in the id starts with helpDialog. </p>
<p>Just like that all the dialogs your heart desires are set and ready to go.</p>
<p>The click function on the help buttons does all the heavy lifting.</p>
<pre class="brush: jscript;">
$('.help').click(function() {
              //strip off prefix of buttin id to get number for dialog
                var helpBtnIdPrefix = 'helpBtn';
                var helpBtnNum = $(this).attr('id').substring((helpBtnIdPrefix.length));

                //offset returns top and left of element
                var helpBtnOffset = $('#helpBtn' + helpBtnNum).offset();
                //width of element
                var helpBtnWidth = $('#helpBtn' + helpBtnNum).width();
                //width of dialog box
                var dialogWidth = $('#helpDialog' + helpBtnNum).dialog('option', 'width');

                //x and y positions of dialog box
                $('#helpDialog' + helpBtnNum).dialog('option','position',[helpBtnOffset.left+helpBtnWidth-dialogWidth,helpBtnOffset.top-$(window).scrollTop()]);
                $('#helpDialog' + helpBtnNum).dialog('open');
            });
</pre>
<p>The script starts by stripping off the prefix on the button id to get to the number of the button as it corresponds to the dialog box. </p>
<p>Then it gets the button offset or left and top position on the document. Next, it gets the button&#8217;s width. All this is used to properly place the dialog over the button.</p>
<p>The x position of the dialog are set using the button&#8217;s left position and width along with the dialog box width. The y position is set by using the button&#8217;s top position minus the window scroll position in case the user scrolled down.</p>
<p>After the math, the dialog is opened.</p>
<p>An extra close button was added at the bottom of the dialog box for user convenience.</p>
<pre class="brush: jscript;">
//added close btn at bottom of dialog
            $('[id^=closeHelp]').click(function() {
                var closeHelpPrefix = 'closeHelp';
                var closeHelpNum = $(this).attr('id').substring((closeHelpPrefix.length));
                $('#helpDialog' + closeHelpNum).dialog('close');
            });
</pre>
<p>Usual recommended jQuery reading:</p>
<div style="height:250px;">
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0596159773" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847196705" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0321647491" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847195121" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
</div>
<p id="demo"><a href="/demos/dialog/position.php"><span>Demo</span></a></p>
<p id="download"><a href="/media/code/dialogposition.zip"><span>Download zip of all files</span></a></p>
<p class="donate">If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.</p>

<!-- Begin PayPal Donations by http://wpstorm.net/ -->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post"><div class="paypal-donations"><input type="hidden" name="cmd" value="_donations" /><input type="hidden" name="business" value="jen@jensbits.com" /><input type="hidden" name="return" value="http://www.jensbits.com/thank-you/" /><input type="hidden" name="item_name" value="Help pay hosting. All donations go to hosting fees for this site." /><input type="hidden" name="currency_code" value="USD" /><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online." /><img alt="" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" /></div></form>
<!-- End PayPal Donations -->



<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2009/11/12/positioning-multiple-jquery-ui-dialogs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Printing a Dynamically Loaded Iframe with jQuery</title>
		<link>http://www.jensbits.com/2009/11/03/printing-a-dynamically-loaded-iframe-with-jquery/</link>
		<comments>http://www.jensbits.com/2009/11/03/printing-a-dynamically-loaded-iframe-with-jquery/#comments</comments>
		<pubDate>Tue, 03 Nov 2009 23:46:26 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[Web development]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=452</guid>
		<description><![CDATA[This is an example of printing a dynamically loaded iframe on a button click. This is useful for printing specific or generated reports or pages without leaving the current page. The iframe to be targeted looks like this and can be placed virtually anywhere in the body tag: &#60;iframe id=&#34;iframeprint&#34; width=&#34;1&#34; height=&#34;1&#34; frameborder=&#34;0&#34;&#62;&#60;/iframe&#62; The button [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>This is an example of printing a dynamically loaded iframe on a button click. This is useful for printing specific or generated reports or pages without leaving the current page.</p>
<p>The iframe to be targeted looks like this and can be placed virtually anywhere in the body tag:</p>
<pre class="brush: xml;">
&lt;iframe id=&quot;iframeprint&quot; width=&quot;1&quot; height=&quot;1&quot; frameborder=&quot;0&quot;&gt;&lt;/iframe&gt;
</pre>
<p>The button to be clicked for printing:</p>
<pre class="brush: xml;">
&lt;p style=&quot;text-align:center&quot;&gt;&lt;a id=&quot;iframeprintbutton&quot; href=&quot;#&quot;&gt;Load and print page in iframe&lt;/a&gt;&lt;/p&gt;
</pre>
<p>The jQuery on the calling page:</p>
<pre class="brush: jscript;">
$().ready(function() {

	$('#iframeprintbutton').click(function() {
		$(&quot;#iframeprint&quot;).attr(&quot;src&quot;, &quot;iframecontents.htm&quot;);
		return false;
     });

});
</pre>
<p>In the example, that page to be printed is in the same directory of the calling page. Use whatever URL will work for the location of the page you want to print. You can use absolute URLs. For example, http://yoursite.com/yourfile.htm.</p>
<p>All that is needed on the page to be printed is a call to the print function.</p>
<pre class="brush: jscript;">
&lt;script language=&quot;javascript&quot;&gt;
 try
            {
                document.execCommand('print', false, null);
            }
            catch(e)
            {
                window.print();
            }
&lt;/script&gt;
</pre>
<p>You could probably use straight javascript here, but I find jQuery quicker and easier to work with.</p>
<p>Usual recommended jQuery reading:</p>
<div style="height: 250px;">
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0596159773" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847196705" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0321647491" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847195121" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
</div>
<p id="demo"><a href="/demos/iframeprint/index.htm"><span>Demo</span></a></p>
<p id="download"><a href="/media/code/iframeprint.zip"><span>Download zip of all files</span></a></p>
<p class="donate">If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.</p>

<!-- Begin PayPal Donations by http://wpstorm.net/ -->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post"><div class="paypal-donations"><input type="hidden" name="cmd" value="_donations" /><input type="hidden" name="business" value="jen@jensbits.com" /><input type="hidden" name="return" value="http://www.jensbits.com/thank-you/" /><input type="hidden" name="item_name" value="Help pay hosting. All donations go to hosting fees for this site." /><input type="hidden" name="currency_code" value="USD" /><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online." /><img alt="" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" /></div></form>
<!-- End PayPal Donations -->



<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2009/11/03/printing-a-dynamically-loaded-iframe-with-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Override &#8220;Print Background Colors and Images&#8221; Option in Browser</title>
		<link>http://www.jensbits.com/2009/09/18/override-printing-of-background-images-and-colors/</link>
		<comments>http://www.jensbits.com/2009/09/18/override-printing-of-background-images-and-colors/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 17:39:36 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[Web development]]></category>
		<category><![CDATA[browser]]></category>
		<category><![CDATA[IE]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=422</guid>
		<description><![CDATA[Internet Explorer and Firefox, to name a few, have an option that allows for the printing of background colors and images. The user can check this option to override the print style sheet and print the backgrounds that were removed to increase legibility, protect copyright, or whatever other reason was necessary. By default, this option [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>Internet Explorer and Firefox, to name a few, have an option that allows for the printing of background colors and images. The user can check this option to override the print style sheet and print the backgrounds that were removed to increase legibility, protect copyright, or whatever other reason was necessary. </p>
<p>By default, this option is off in browsers and the user has to manually check a box. In IE it is under Tools, Internet Options, Advanced, Printing. In Firefox it is in Page Setup of the Print Preview window.</p>
<p>Here is what is looks like in FF:<br />
<img src="/images/ff_printsettings.gif" alt="Firefox print settings" /><br />
To prevent the browser from printing backgrounds when this is checked, add the following to your print style sheet:</p>
<pre class="brush: css;">
* {
  background-color: white !important;
  background-image: none !important;
  }
</pre>
<p>Now, I&#8217;m not one to take all control away from the user, but there are situations when you must.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2009/09/18/override-printing-of-background-images-and-colors/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Session Timeout Warning PHP Example with jQuery/JS</title>
		<link>http://www.jensbits.com/2009/09/07/session-timeout-warning-php-example-with-jqueryjs/</link>
		<comments>http://www.jensbits.com/2009/09/07/session-timeout-warning-php-example-with-jqueryjs/#comments</comments>
		<pubDate>Tue, 08 Sep 2009 00:45:37 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[Web development]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[browser]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=386</guid>
		<description><![CDATA[Updated 11-Jan-2010: Improved ability to adjust timeouts and simplified code a bit. Detecting and warning a user of their session timing out can come in handy and, in some cases, may be necessary. Here is one way of doing this with jQuery/javascript and PHP. There may be a better way to do this, so take [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<blockquote><p>Updated 11-Jan-2010: Improved ability to adjust timeouts and simplified code a bit.</p></blockquote>
<p>Detecting and warning a user of their session timing out can come in handy and, in some cases, may be necessary. Here is one way of doing this with jQuery/javascript and PHP. There may be a better way to do this, so take this as an example.<br />
There is a post on a <a href="/2009/09/12/session-timeout-warning-with-coldfusion-and-jqueryjs/">ColdFusion session timeout warning</a> that works in a similar manner.</p>
<h3>Session Defined: Start to Finish</h3>
<p>A session is defined as when a user begins and ends using or visiting a web site. It can be unlimited in length or strictly defined by a timeout period. If the site requires a log in or accesses sensitive data, it should time out after a period of inactivity. They can end a session by logging out or closing the browser.</p>
<p>Inactivity means the user has done nothing, made no requests of the web server, during a specified time. Ajax requests usually do not count. There are other posts out there that detail how to check for session expiration with Ajax requests.</p>
<h3>Demo</h3>
<p>The session time left is determined by the server, and, if you want to poll the server with an Ajax request, go for it. This demo uses javascript to keep track of the time left in the session.</p>
<p>The demo uses a simple log in with session timing handled by jquery and javascript. When the session expiration approaches, the user is warned and given an opportunity to restart the session. If the session time limit is reached, the user is prompted to log in again. If they ignore that prompt, the page automatically redirects to the log in form. In the demo this sequence of events takes 40 seconds to complete and is broken down as follows:</p>
<ol>
<li><em>Session timeout:</em> 30 seconds</li>
<li><strong>Timeout warning:</strong> 20 seconds</li>
<li><strong>Session expired warning:</strong> 10 seconds</li>
<li><strong>Redirect to log in page: </strong>10 seconds</li>
</ol>
<h3>Interrupting the User</h3>
<p>The user&#8217;s attention can be diverted away from other open windows to the eminent session expiration by using a javascript alert in place of the jquery dialog box. Personal preference.</p>
<h3>Code Breakdown</h3>
<p>The log in page checks for a query string variable called &#8216;expired&#8217; and sets the loggedin cookie to false. This is there because the code is going to control the expiration of the session eliminating the need to compensate for browser latency. The actual session start time the time the page loads can differ by several seconds. To avoid having to add time to the session or any other fancy guesswork, when the allotted session time has expired according to the javascript timer on the page, they are done &#8211; session over.</p>
<p>If they are logged in, they get bumped to the index page. The rest is the logic that handles the log in form.</p>
<p>Note: I would not recommend handling a log in form this way. This is for demonstration only.</p>
<pre class="brush: php;">
//if query string contains expired var &amp; it = true, set loggedin cookie as false
//else if loggedin cookie exists and is set to true, send to index page
if (isset($_GET['expired']) &amp;&amp; $_GET['expired'] == 'true')
    {
        setcookie(&quot;loggedin&quot;, &quot;false&quot;, time()+30);
    }
elseif (isset($_COOKIE['loggedin']) &amp;&amp; $_COOKIE['loggedin'] == 'true')
    {
        header(&quot;Location: index.php&quot;);
        exit;
    }
//log in logic
if (isset($_POST['username']) &amp;&amp; isset($_POST['pw']) &amp;&amp; $_POST['username'] == &quot;session&quot; &amp;&amp; $_POST['pw'] == &quot;test&quot;)
    {
        setcookie(&quot;loggedin&quot;, &quot;true&quot;, time()+30);
        header(&quot;Location: index.php&quot;);
        exit;
    }
</pre>
<p>Other than the log in form and a message for the user, that&#8217;s all there is to the log in page.</p>
<h3>Handling Session Timeout</h3>
<p>The index page handles the session timeout code. This could be a separate javascript included in every page. The first block simply determines if they are logged in. If they are not, send them to the login page. If they are, refresh the cookie timeout by resetting it.</p>
<pre class="brush: php;">
if (!isset($_COOKIE['loggedin']) || (isset($_COOKIE['loggedin']) &amp;&amp; $_COOKIE['loggedin'] == 'false'))
    {
        header(&quot;Location: login.php&quot;);
        exit;
    }
elseif (isset($_COOKIE['loggedin']) &amp;&amp; $_COOKIE['loggedin'] == 'true')
    {
    //user is logged in, page was refreshed or reloaded to restart session so reset cookie
    setcookie(&quot;loggedin&quot;, &quot;true&quot;, time()+30);
    }
?&gt;
</pre>
<p>Now the time variables are set and the a javascript timer is set to check the session every 10 seconds.<br />
Javascript uses milliseconds so for clarity the time intervals multiply the number of seconds by 1,000. You could put 10000 in for 10 seconds but I think 10*1000 helps me determine that it is 10 seconds quite a bit faster. Do what is comfortable for you.</p>
<p>Also, a flag is set to determine if the warning dialog box has been opened and the countdown has begun.</p>
<pre class="brush: jscript;">
//event to check session time variable declaration
var checkSessionTimeEvent;

$(document).ready(function() {
	//event to check session time left (times 1000 to convert seconds to milliseconds)
    checkSessionTimeEvent = setInterval(&quot;checkSessionTime()&quot;,10*1000);
});

//Your timing variables in number of seconds

//total length of session in seconds
var sessionLength = 30;
//time warning shown (10 = warning box shown 10 seconds before session starts)
var warning = 10;
//time redirect forced (10 = redirect forced 10 seconds after session ends)
var forceRedirect = 10; 

//time session started
var pageRequestTime = new Date();

//session timeout length
var timeoutLength = sessionLength*1000;

//set time for first warning, ten seconds before session expires
var warningTime = timeoutLength - (warning*1000);

//force redirect to log in page length (session timeout plus 10 seconds)
var forceRedirectLength = timeoutLength + (forceRedirect*1000);

//set number of seconds to count down from for countdown ticker
var countdownTime = warning;

//warning dialog open; countdown underway
var warningStarted = false;
</pre>
<p>The checkSessionTime function is what gets fired off every 10 seconds by the timer. It does a time comparison and opens the dialog boxes that warn the user.</p>
<pre class="brush: jscript;">
function checkSessionTime()
{
	//get time now
	var timeNow = new Date(); 

	//event create countdown ticker variable declaration
	var countdownTickerEvent; 	

	//difference between time now and time session started variable declartion
	var timeDifference = 0;

	timeDifference = timeNow - pageRequestTime;

    if (timeDifference &gt; warningTime &amp;&amp; warningStarted === false)
        {
            //call now for initial dialog box text (time left until session timeout)
            countdownTicker(); 

            //set as interval event to countdown seconds to session timeout
            countdownTickerEvent = setInterval(&quot;countdownTicker()&quot;, 1000);

            $('#dialogWarning').dialog('open');
            warningStarted = true;
        }
    else if (timeDifference &gt; timeoutLength){
    		//close warning dialog box
            if ($('#dialogWarning').dialog('isOpen')) $('#dialogWarning').dialog('close');

            $('#dialogExpired').dialog('open');

             //clear (stop) countdown ticker
            clearInterval(countdownTickerEvent);
        }

    if (timeDifference &gt; forceRedirectLength)
     	{
           //clear (stop) checksession event
            clearInterval(checkSessionTimeEvent);

            //force relocation
            window.location=&quot;login.php?expired=true&quot;;
        }
}
</pre>
<p>The countdownTicker function provides a countdown inside the warning dialog box to prompt the user to act now. It uses a timer that fires every second for a 5,4,3,2,1 effect inside the dialog box.</p>
<pre class="brush: jscript;">
function countdownTicker()
{
	//put countdown time left in dialog box
	$(&quot;span#dialogText-warning&quot;).html(countdownTime);

	//decrement countdownTime
	countdownTime--;
}
</pre>
<p>And, the dialog boxes either allow the user to reload the page or, if they did nothing when the warning popped up, it logs them out by redirecting to the log in page with the expired variable in the query string. Also, thanks to scube&#8217;s debugging, it now redirects to the log in if they hit the close button on the dialog box rather than the Login button.</p>
<pre class="brush: jscript;">
$(function(){
                // jQuery UI Dialog
                $('#dialogWarning').dialog({
                    autoOpen: false,
                    width: 400,
                    modal: true,
                    resizable: false,
                    buttons: {
                        &quot;Restart Session&quot;: function() {
                            location.reload();
                        }
                    }
                });

                $('#dialogExpired').dialog({
                    autoOpen: false,
                    width: 400,
                    modal: true,
                    resizable: false,
                    close: function() {
                            window.location=&quot;login.php?expired=true&quot;;
                        },
                    buttons: {
                        &quot;Login&quot;: function() {
                            window.location=&quot;login.php?expired=true&quot;;
                        }
                    }
                });
});
</pre>
<p>The dialog box contents are at the bottom of the page but they could be just about anywhere in the body.</p>
<pre class="brush: xml;">
&lt;!--Dialog box contents--&gt;
&lt;div id=&quot;dialogExpired&quot; title=&quot;Session (Page) Expired!&quot;&gt;&lt;p&gt;&lt;span class=&quot;ui-icon ui-icon-alert&quot; style=&quot;float:left; margin:0 7px 0 0;&quot;&gt;&lt;/span&gt; Your session has expired!&lt;p id=&quot;dialogText-expired&quot;&gt;&lt;/p&gt;&lt;/div&gt;

&lt;div id=&quot;dialogWarning&quot; title=&quot;Session (Page) Expiring!&quot;&gt;&lt;p&gt;&lt;span class=&quot;ui-icon ui-icon-alert&quot; style=&quot;float:left; margin:0 7px 0 0;&quot;&gt;&lt;/span&gt; Your session will expire in &lt;span id=&quot;dialogText-warning&quot;&gt;&lt;/span&gt; seconds!&lt;/div&gt;
</pre>
<p>Remember, this is just one example. There are other ways to do this. Use this, improve this, or roll your own.</p>
<p>Usual recommended jQuery and PHP reading:</p>
<div style="height: 250px;">
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847196705" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0321647491" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847195121" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0764557467" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
</div>
<p id="demo"><a href="/demos/session/php/index.php"><span>Demo</span></a></p>
<p id="download"><a href="/media/code/session-expire-php.zip"><span>Download zip of all files</span></a></p>
<p class="donate">If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.</p>

<!-- Begin PayPal Donations by http://wpstorm.net/ -->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post"><div class="paypal-donations"><input type="hidden" name="cmd" value="_donations" /><input type="hidden" name="business" value="jen@jensbits.com" /><input type="hidden" name="return" value="http://www.jensbits.com/thank-you/" /><input type="hidden" name="item_name" value="Help pay hosting. All donations go to hosting fees for this site." /><input type="hidden" name="currency_code" value="USD" /><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online." /><img alt="" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" /></div></form>
<!-- End PayPal Donations -->



<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2009/09/07/session-timeout-warning-php-example-with-jqueryjs/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
	</channel>
</rss>
