<?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; jquery</title>
	<atom:link href="http://www.jensbits.com/tag/jquery/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>jQuery Modal Dialog Close on Overlay Click</title>
		<link>http://www.jensbits.com/2010/06/16/jquery-modal-dialog-close-on-overlay-click/</link>
		<comments>http://www.jensbits.com/2010/06/16/jquery-modal-dialog-close-on-overlay-click/#comments</comments>
		<pubDate>Wed, 16 Jun 2010 15:03:51 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=743</guid>
		<description><![CDATA[You may want a modal dialog to close if the overlay is clicked on the page. One way of doing that is to bind a click event to the document and fire it only when the dialog box does not have focus. This example uses a variable that is flipped back and forth depending on [...]


Related posts:<ol><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>You may want a modal dialog to close if the overlay is clicked on the page. One way of doing that is to bind a click event to the document and fire it only when the dialog box does not have focus.</p>
<p>This example uses a variable that is flipped back and forth depending on whether or not the dialog box had regained focus. When the dialog box gains focus, the closedialog variable is set to 0 (zero) to prevent the dialog.close method in the overlayclickclose function from being called. The overlayclickclose function is bound to the click event of the document.</p>
<p>The closedialog variable is also set to 1 (one) in the overlayclickclose function so that it will fire when there is a click outside the dialog box.</p>
<p>The dialog box open and close events bind and unbind the click event to the document so that it is only bound when the dialog box is open.</p>
<pre class="brush: jscript;">
			   var closedialog;

			   function overlayclickclose() {
					if (closedialog) {
						$('#mydialog').dialog('close');
            		}
					//set to one because click on dialog box sets to zero
					closedialog = 1;
        		}

			$('#mydialog').dialog({
				bgiframe: true,
				autoOpen: true,
				modal: true,
				width: 500,
				resizable: false,
				open: function(){closedialog = 1;$(document).bind('click', overlayclickclose);},
				focus: function(){closedialog = 0;},
				close: function(){$(document).unbind('click');},
				buttons: {
					Submit: function(){
						$(this).dialog('close');
					}
				}
			});

		$('#opendialog').click(function() {
                       $('#mydialog').dialog('open');
                       closedialog = 0;
            });
</pre>
<p>The html for the dialog box includes a couple of radio buttons and a submit button just for demonstration. They do not really do anything in this example. Below is the complete code example.</p>
<pre class="brush: xml;">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;title&gt;Close Dialog on Overlay Click&lt;/title&gt;
&lt;style type=&quot;text/css&quot; media=&quot;screen&quot;&gt;
body {background-color: #efefef;font-family: &quot;Trebuchet MS&quot;,sans-serif;font-size: 16px;}
h1,h2,p {padding: 5px;}
h1,h2{font-size: 18px; color: #666666;}
.container {width: 50%;margin-left: 25%;margin-top:2%;background: #ffffff;border: 4px solid #cccccc;}
#mydialog{font-size:80%}
&lt;/style&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;css/redmond/jquery-ui-1.8.2.custom.css&quot;&gt;

&lt;script language=&quot;javascript&quot; type=&quot;text/javascript&quot; src=&quot;js/jquery-1.4.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script language=&quot;javascript&quot; type=&quot;text/javascript&quot; src=&quot;js/jquery-ui-1.8.2.custom.min.js&quot;&gt;&lt;/script&gt;
&lt;script language=&quot;javascript&quot; type=&quot;text/javascript&quot;&gt;
$().ready( function () {
			   var closedialog;

			   function overlayclickclose() {
					if (closedialog) {
						$('#mydialog').dialog('close');
            		}
					//set to one because click on dialog box sets to zero
					closedialog = 1;
        		}

			$('#mydialog').dialog({
				bgiframe: true,
				autoOpen: true,
				modal: true,
				width: 500,
				resizable: false,
				open: function(){closedialog = 1;$(document).bind('click', overlayclickclose);},
				focus: function(){closedialog = 0;},
				close: function(){$(document).unbind('click');},
				buttons: {
					Submit: function(){
						$(this).dialog('close');
					}
				}
			});

		$('#opendialog').click(function() {
                       $('#mydialog').dialog('open');
		        closedialog = 0;
            });
});
&lt;/script&gt;

&lt;/head&gt;
&lt;body&gt;
&lt;div class=&quot;container&quot;&gt;

&lt;h1&gt;Close Dialog on Overlay Click Test page&lt;/h1&gt;
&lt;p&gt;Dialog will close if overlay is clicked but not if anything inside of dialog is clicked.&lt;/p&gt;
&lt;p&gt;&lt;a id=&quot;opendialog&quot; href=&quot;#&quot;&gt;Open dialog&lt;/a&gt;&lt;/p&gt;
&lt;div id=&quot;mydialog&quot; title=&quot;Overlay Click Close&quot;&gt;
		&lt;p&gt;Demo of overlay close on click. Submit button will close dialog and nothing else.&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&gt;

&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>Recommended:</h2>
<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=1935182323" 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>
</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=0321509021" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
</div>
<p id="demo"><a href="/demos/dialog/overlayclose/"><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/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/06/16/jquery-modal-dialog-close-on-overlay-click/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using jQuery Autocomplete to Populate Another Autocomplete &#8211; ASP.NET, ColdFusion, and PHP Examples</title>
		<link>http://www.jensbits.com/2010/05/29/using-jquery-autocomplete-to-populate-another-autocomplete-asp-net-coldfusion-and-php-examples/</link>
		<comments>http://www.jensbits.com/2010/05/29/using-jquery-autocomplete-to-populate-another-autocomplete-asp-net-coldfusion-and-php-examples/#comments</comments>
		<pubDate>Sat, 29 May 2010 20:41:53 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[ColdFusion]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=730</guid>
		<description><![CDATA[As requested, this post covers using one jquery autocomplete to populate another jquery autocomplete on the same page. This example will use a jquery autocomplete to choose a state then, based on the state, another jquery autocomplete will be populated with zip codes for that state. Basically, the state chosen gets used as a filter [...]


Related posts:<ol><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>
<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>
<li><a href='http://www.jensbits.com/2009/10/04/jquery-ajax-and-jquery-post-form-submit-examples-with-php/' rel='bookmark' title='Permanent Link: jQuery.ajax and jQuery.post Form Submit Examples with PHP'>jQuery.ajax and jQuery.post Form Submit Examples with PHP</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>As requested, this post covers using one jquery autocomplete to populate another jquery autocomplete on the same page. This example will use a jquery autocomplete to choose a state then, based on the state, another jquery autocomplete will be populated with zip codes for that state. Basically, the state chosen gets used as a filter in the query for the second autocomplete.</p>
<h2>Form</h2>
<p>The form for the examples is the same with fields for the autocompletes (state and zip_code) plus input fields for the values returned by the autocompletes.</p>
<pre class="brush: xml;">
&lt;form action=&quot;YOUR-FILE-HERE&quot;  method=&quot;post&quot;&gt;
&lt;fieldset&gt;
&lt;legend&gt;jQuery UI Multi-Autocomplete Example&lt;/legend&gt;
&lt;p&gt;Start typing the name of a state or territory of the United States&lt;/p&gt;

&lt;p&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&gt;&lt;label for=&quot;zip_code&quot;&gt;Zip (only Zips from state selected above): &lt;/label&gt;
&lt;input type=&quot;text&quot; id=&quot;zip_code&quot; name=&quot;zip_code&quot; maxlength=&quot;5&quot; size=&quot;15&quot; /&gt;&lt;/p&gt;

&lt;p class=&quot;ui-widget&quot;&gt;&lt;label for=&quot;city&quot;&gt;City:&lt;/label&gt;
&lt;input readonly=&quot;readonly&quot; type=&quot;text&quot; id=&quot;city&quot; name=&quot;city&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>
<h2>jQuery</h2>
<p>The jquery is also the same for each example. Notice that the zip_code field is initially disabled to prevent entry before the results have been filtered.</p>
<p>Also, note that the source and secondary URL extension will have to be modified depending on the language you are using.</p>
<pre class="brush: jscript;">
$(function() {

			//clear values on refresh
			$('#abbrev').val(&quot;&quot;);
			$('#city').val(&quot;&quot;);

			$(&quot;#zip_code&quot;).attr('disabled', true);

			$(&quot;#state&quot;).autocomplete({
				source: &quot;states.[cfm|aspx|php]&quot;,
				minLength: 2,
				select: function(event, ui) {
					$('#state_id').val(ui.item.id);
					$('#abbrev').val(ui.item.abbrev);
					$(&quot;#zip_code&quot;).attr('disabled', false);
				},
				change: function(event, ui){
					secondary_url = &quot;zips.[cfm|aspx|php]?filter=&quot; + ui.item.abbrev;
					$(&quot;#zip_code&quot;).autocomplete(&quot;option&quot;, &quot;source&quot;, secondary_url);
				}
			});

			$(&quot;#zip_code&quot;).autocomplete({
				source: &quot;&quot;,
				minLength: 2,
				select: function(event,ui){
					$('#city').val(ui.item.city);
				}
			});

		});
</pre>
<h2>Processing</h2>
<p>Each programming language differs slightly in the processing. And, since there are hundreds of zip codes per state, the results are limited to 20. If the zip code desired is not returned in the top 20 after entering the minimum 2 characters, typing more characters will yield more precise results.</p>
<h3>ASP.NET</h3>
<p>Refer to the <a href="/2010/04/14/jquery-ui-autocomplete-widget-with-asp-net/">complete example of using the jquery autocomplete with ASP.NET</a> for more information. </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 Zip
        Public zipcode As String
		Public label As String
		Public value As String
        Public city As String
    End Class

    Private Function JSONData(ByVal term As String) As String

        Dim zipArray As New ArrayList
        Dim index As Integer = 0

        Dim mySql As String
        Dim objConn As New SqlConnection(&quot;Server=YOUR-SERVER;Database=YOUR-DATABASE;User ID=YOUR-USERID;Password=YOUR-PASSWORD&quot;)
        Dim myds As New DataSet(&quot;Zips&quot;)
        mySql = &quot;SELECT TOP 20 zip, city FROM zips WHERE abbrev = '&quot; + Request.QueryString(&quot;filter&quot;) + &quot;' AND zip like '&quot; + term + &quot;%'&quot;

        objConn.Open()

        Dim adapter As New SqlClient.SqlDataAdapter(mySql, objConn)
        adapter.Fill(myds, &quot;Zips&quot;)
        For Each dr As DataRow In myds.Tables(0).Rows
            Dim zp As New Zip()
            zp.label = dr(&quot;zip&quot;).ToString() &amp; &quot; &quot; &amp; dr(&quot;city&quot;).ToString()
            zp.value = dr(&quot;zip&quot;).ToString()
            zp.city = dr(&quot;city&quot;).ToString()
            zipArray.Add(zp)
        Next

        objConn.Close()

        Return serializer.Serialize(zipArray)
    End Function

&lt;/script&gt;
</pre>
<p id="demo"><a href="http://cf-jensbits.com/demos/autocomplete_asp/zipselect.aspx" onclick="_gaq.push(['_link', 'http://cf-jensbits.com/demos/autocomplete_asp/zipselect.aspx']); return false;"><br />
<span>Demo</span></a></p>
<h3>ColdFusion</h3>
<p>Refer to the <a href="/2010/03/18/jquery-ui-autocomplete-with-coldfusion/">complete example of using the jquery autocomplete with ColdFusion</a> for more information.</p>
<p>ColdFusion&#8217;s serializeJSON function has an odd bug that will not let you send numbers as strings. This turns the zip codes into numbers which we do not want. To workaround this, I added a space in front of the zip code then removed it from the JSON output with the Replace function. Not the best idea, but it works.</p>
<pre class="brush: coldfusion;">
&lt;cfset returnArray = ArrayNew(1) /&gt;

&lt;cfquery name=&quot;qryStates&quot; dataSource=&quot;autocomplete&quot;&gt;
	SELECT TOP 20 zip, city FROM zips WHERE abbrev = '#URL.filter#' AND zip like '#URL.term#%'
&lt;/cfquery&gt;

&lt;cfloop query=&quot;qryStates&quot;&gt;
	&lt;cfset zipsStruct = StructNew() /&gt;
    &lt;cfset zipsStruct[&quot;label&quot;] = ToString(zip) &amp; &quot; &quot; &amp; city /&gt;
    &lt;!---Had to add leading space to prevent serializeJSON from turning zip into number---&gt;
    &lt;cfset zipsStruct[&quot;value&quot;] = &quot; &quot; &amp; zip /&gt;
    &lt;cfset zipsStruct[&quot;city&quot;] = city /&gt;

    &lt;cfset ArrayAppend(returnArray,zipsStruct) /&gt;
&lt;/cfloop&gt;

&lt;cfoutput&gt;
&lt;!---replaced all spaces after quotes with just quotes in JSON to remove leading space applied to zip---&gt;
#Replace(serializeJSON(returnArray),'&quot; ','&quot;',&quot;all&quot;)#
&lt;/cfoutput&gt;
</pre>
<p id="demo"><a href="http://cf-jensbits.com/demos/autocomplete/zipselect.cfm" onclick="_gaq.push(['_link', 'http://cf-jensbits.com/demos/autocomplete/zipselect.cfm']); return false;"><br />
<span>Demo</span></a></p>
<h3>PHP</h3>
<p>Refer to the <a href="/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/">complete example of using the jquery autocomplete with PHP</a> for more information.</p>
<p>This PHP example using SQL Server as the database. The complete example linked above uses MySQL.</p>
<pre class="brush: php;">
&lt;?php
$dbhost = 'YOUR_SERVER';
$dbuser = 'YOUR_USERNAME';
$dbpass = 'YOUR_PASSWORD';
$dbname = 'YOUR_DATABASE_NAME';

$conn = mssql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mssql');
mssql_select_db($dbname);

$return_arr = array();

if ($conn)
{
	$fetch = mssql_query(&quot;SELECT TOP 20 zip, city FROM zips WHERE abbrev = '&quot; . $_GET['filter'] . &quot;' AND zip like '&quot; . $_GET['term'] . &quot;%'&quot;); 

	/* Retrieve and store in array the results of the query.*/

	while ($row = mssql_fetch_array($fetch)) {
		$row_array['label'] = $row['zip'] . &quot; &quot; . $row['city'];
		$row_array['value'] = $row['zip'];
		$row_array['city'] = $row['city'];

        array_push($return_arr,$row_array);
    }

}
/* Free connection resources. */
mssql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($return_arr);

?&gt;
</pre>
<p id="demo"><a href="http://cf-jensbits.com/demos/autocomplete_php/zipselect.php" onclick="_gaq.push(['_link', 'http://cf-jensbits.com/demos/autocomplete_php/zipselect.php']); return false;"><br />
<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/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>
<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>
<li><a href='http://www.jensbits.com/2009/10/04/jquery-ajax-and-jquery-post-form-submit-examples-with-php/' rel='bookmark' title='Permanent Link: jQuery.ajax and jQuery.post Form Submit Examples with PHP'>jQuery.ajax and jQuery.post Form Submit Examples with PHP</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2010/05/29/using-jquery-autocomplete-to-populate-another-autocomplete-asp-net-coldfusion-and-php-examples/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<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>jQuery UI Autocomplete Widget with PHP and MySQL</title>
		<link>http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/</link>
		<comments>http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 02:31:43 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[jquery]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=660</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 post, I did one with PHP as the backend. The jQuery UI folks have released an autocomplete widget that is pretty slick. This example uses the json_encode function [...]


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/04/14/jquery-ui-autocomplete-widget-with-asp-net/' rel='bookmark' title='Permanent Link: jQuery UI Autocomplete Widget with ASP.NET VB'>jQuery UI Autocomplete Widget with ASP.NET VB</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> post, I did one with PHP as the backend.</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 json_encode function in PHP 5. If you have an earlier version of PHP, you will have to roll your own JSON string.<br />
<img src="/images/autocomplete_php.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;&lt;?php echo $PHP_SELF;?&gt;&quot;  method=&quot;post&quot;&gt;
&lt;fieldset&gt;
&lt;legend&gt;jQuery UI Autocomplete Example - PHP 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: php;">
&lt;?php
if (isset($_POST['submit'])) {
echo &quot;&lt;p&gt;&quot;;
	while (list($key,$value) = each($_POST)){
	echo &quot;&lt;strong&gt;&quot; . $key . &quot;&lt;/strong&gt; = &quot;.$value.&quot;&lt;br /&gt;&quot;;
	}
echo &quot;&lt;/p&gt;&quot;;
}
?&gt;
</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 PHP 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 PHP pages return the data after a few steps:</p>
<ol>
<li>It queries the database</li>
<li>Loops an array of the query results adding each row to a return array</li>
<li>Outputs the array as JSON data</li>
</ol>
<p>The states.php 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. And, of course, you will have to make your own connection to your MySQL database before running the query.</p>
<pre class="brush: php;">
$return_arr = array();

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

/* If connection to database, run sql statement. */
if ($conn)
{
	$fetch = mysql_query(&quot;SELECT * FROM states where state like '%&quot; . $_GET['term'] . &quot;%'&quot;); 

	/* Retrieve and store in array the results of the query.*/

	while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
		$row_array['id'] = $row['id'];
		$row_array['value'] = $row['state'];
		$row_array['abbrev'] = $row['abbrev'];

        array_push($return_arr,$row_array);
    }

}

/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($return_arr);
</pre>
<p>The states_abbrev.php 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: php;">
$return_arr = array();

/* If connection to database, run sql statement. */
if ($conn)
{
	$fetch = mysql_query(&quot;SELECT * FROM states where state like '%&quot; . $_GET['term'] . &quot;%'&quot;); 

	/* Retrieve and store in array the results of the query.*/

	while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
		$row_array['label'] = $row['state'];
		$row_array['value'] = $row['abbrev'];

        array_push($return_arr,$row_array);
    }

}
/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($return_arr);
</pre>
<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=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=0470413964" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe></p>
</div>
</div>
<p id="demo"><a href="/demos/autocomplete/" ><span>Demo</span></a></p>
<p id="download"><a href="/media/code/autocomplete_PHP_jensbits.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/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/04/14/jquery-ui-autocomplete-widget-with-asp-net/' rel='bookmark' title='Permanent Link: jQuery UI Autocomplete Widget with ASP.NET VB'>jQuery UI Autocomplete Widget with ASP.NET VB</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/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>jQuery UI Autocomplete Widget with ColdFusion</title>
		<link>http://www.jensbits.com/2010/03/18/jquery-ui-autocomplete-with-coldfusion/</link>
		<comments>http://www.jensbits.com/2010/03/18/jquery-ui-autocomplete-with-coldfusion/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 19:58:35 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[ColdFusion]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=649</guid>
		<description><![CDATA[You may also be interested in the jQuery UI Autocomplete Widget with PHP and MySQL or the jQuery UI Autocomplete Widget with ASP.NET VB post. Also, check out the Using jQuery Autocomplete to Populate Another Autocomplete post. The jQuery UI folks have released an autocomplete widget that is pretty slick. Using it with ColdFusion is [...]


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/04/14/jquery-ui-autocomplete-widget-with-asp-net/' rel='bookmark' title='Permanent Link: jQuery UI Autocomplete Widget with ASP.NET VB'>jQuery UI Autocomplete Widget with ASP.NET VB</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>
</ol>]]></description>
			<content:encoded><![CDATA[<blockquote><p>You may also be interested in the <a href="/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/"> jQuery UI Autocomplete Widget with PHP and MySQL</a> or the <a href="/2010/04/14/jquery-ui-autocomplete-widget-with-asp-net/">jQuery UI Autocomplete Widget with ASP.NET VB</a> post. Also, check out 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>The jQuery UI folks have released an <a href=" http://jqueryui.com/demos/autocomplete/">autocomplete widget</a> that is pretty slick. Using it with ColdFusion is a snap. This example uses the serializeJSON function in ColdFusion 8. If you have an earlier version of CF, you will have to find a <a href="http://www.epiphantastic.com/cfjson/">cfc that can build a JSON string</a> for you. There are several freely available cfc&#8217;s that do it for you.<br />
<img src="/images/autocomplete.gif" alt="autocomplete" /><br />
This example will use US states and territories to populate the autocomplete. It will also demostrate 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;index.cfm&quot;  method=&quot;post&quot;&gt;
&lt;fieldset&gt;
&lt;legend&gt;jQuery UI Autocomplete Example - ColdFusion 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: coldfusion;">
&lt;cfdump var=&quot;#form#&quot; label=&quot;Form Fields&quot; /&gt;
</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.cfm&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.cfm&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 ColdFusion 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 ColdFusion pages return the data after a few steps:</p>
<ol>
<li>It queries the database</li>
<li>Loops the query, adding each row to a structure that is appended to an array</li>
<li>Outputs the array as JSON data</li>
</ol>
<p>The states.cfm file returns the id field, the state field as &#8216;label&#8217;, and the abbrev field. These values are placed in the appropriate text boxes by the autocomplete jQuery function. </p>
<pre class="brush: coldfusion;">
&lt;cfset returnArray = ArrayNew(1) /&gt;

&lt;cfquery name=&quot;qryStates&quot; dataSource=&quot;autocomplete&quot;&gt;
    Select * from states where state like '%#URL.term#%'
&lt;/cfquery&gt;

&lt;cfloop query=&quot;qryStates&quot;&gt;
    &lt;cfset statesStruct = StructNew() /&gt;
    &lt;cfset statesStruct[&quot;id&quot;] = id /&gt;
    &lt;cfset statesStruct[&quot;label&quot;] = state /&gt;
    &lt;cfset statesStruct[&quot;abbrev&quot;] = abbrev /&gt;

    &lt;cfset ArrayAppend(returnArray,statesStruct) /&gt;
&lt;/cfloop&gt;

&lt;cfoutput&gt;
#serializeJSON(returnArray)#
&lt;/cfoutput&gt;
</pre>
<p>Unfortunately, the ColdFusion function serializeJSON does not put query results in the format that javascript likes. That&#8217;s why we have to do the hokey-pokey with the structure and array.</p>
<p>The states_abbrev.cfm 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: coldfusion;">
&lt;cfset returnArray = ArrayNew(1) /&gt;

&lt;cfquery name=&quot;qryStates&quot; dataSource=&quot;autocomplete&quot;&gt;
    Select * from state where state like '%#URL.term#%'
&lt;/cfquery&gt;

&lt;cfloop query=&quot;qryStates&quot;&gt;
    &lt;cfset statesStruct = StructNew() /&gt;
    &lt;cfset statesStruct[&quot;label&quot;] = state /&gt;
    &lt;cfset statesStruct[&quot;value&quot;] = abbrev /&gt;

    &lt;cfset ArrayAppend(returnArray,statesStruct) /&gt;
&lt;/cfloop&gt;

&lt;cfoutput&gt;
#serializeJSON(returnArray)#
&lt;/cfoutput&gt;
</pre>
<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/autocomplete/" onclick="_gaq.push(['_link', 'http://cf-jensbits.com/demos/autocomplete/']); 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/04/14/jquery-ui-autocomplete-widget-with-asp-net/' rel='bookmark' title='Permanent Link: jQuery UI Autocomplete Widget with ASP.NET VB'>jQuery UI Autocomplete Widget with ASP.NET VB</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>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2010/03/18/jquery-ui-autocomplete-with-coldfusion/feed/</wfw:commentRss>
		<slash:comments>5</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>
	</channel>
</rss>
