<?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</title>
	<atom:link href="http://www.jensbits.com/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>Clicks and Impressions from Google Adwords API using ColdFusion</title>
		<link>http://www.jensbits.com/2010/07/18/clicks-and-impressions-from-google-adwords-api-using-coldfusion/</link>
		<comments>http://www.jensbits.com/2010/07/18/clicks-and-impressions-from-google-adwords-api-using-coldfusion/#comments</comments>
		<pubDate>Sun, 18 Jul 2010 18:28:22 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[Adwords]]></category>
		<category><![CDATA[ColdFusion]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=814</guid>
		<description><![CDATA[Requests for simple data like clicks and impressions from the Google Adwords API can be made via SOAP requests. For more complex data and calculations, the client libraries are more aptly suited. This example does not use the sandbox. Calls to it will counts against the Adwords units. It also uses the latest version of [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>Requests for simple data like clicks and impressions from the <a href="http://code.google.com/apis/adwords/v2009/docs/start.html">Google Adwords API</a> can be made via SOAP requests. For more complex data and calculations, the <a href="http://code.google.com/apis/adwords/v2009/docs/clientlibraries.html">client libraries</a> are more aptly suited.</p>
<p>This example does not use the sandbox. Calls to it will counts against the Adwords units. It also uses the latest version of the API, version v201003.</p>
<p>The requests require an authorization token which can be obtained via the ClientLogin method. Store this token in a session or application variable to prevent a CAPTCHA challend from Google for multiple authorization requests.</p>
<pre class="brush: coldfusion;">
&lt;cfif NOT StructKeyExists(application, &quot;adw_loginAuth&quot;)&gt;
	&lt;cfset googleLogin(api.email,api.password) /&gt;
&lt;/cfif&gt;

&lt;cffunction name=&quot;googleLogin&quot; access=&quot;private&quot; hint=&quot;GA account authorization&quot;&gt;
        &lt;cfargument name=&quot;email&quot; type=&quot;string&quot; required=&quot;yes&quot; default=&quot;&quot;&gt;
        &lt;cfargument name=&quot;password&quot; type=&quot;string&quot;required=&quot;yes&quot; default=&quot;&quot;&gt;
        &lt;cfargument name=&quot;gaLoginUrl&quot; type=&quot;string&quot; required=&quot;no&quot; default=&quot;https://www.google.com/accounts/ClientLogin&quot;&gt;

        &lt;cfset var loginAuth = &quot;&quot; /&gt;

        &lt;cfhttp url=&quot;#arguments.gaLoginUrl#&quot; method=&quot;post&quot;&gt;
            &lt;cfhttpparam name=&quot;accountType&quot; type=&quot;url&quot; value=&quot;GOOGLE&quot;&gt;
            &lt;cfhttpparam name=&quot;Email&quot; type=&quot;url&quot; value=&quot;#arguments.email#&quot;&gt;
            &lt;cfhttpparam name=&quot;Passwd&quot; type=&quot;url&quot; value=&quot;#arguments.password#&quot;&gt;
            &lt;cfhttpparam name=&quot;service&quot; type=&quot;url&quot; value=&quot;adwords&quot;&gt;
            &lt;cfhttpparam name=&quot;source&quot; type=&quot;url&quot; value=&quot;my-adwords-not-yours&quot;&gt;
        &lt;/cfhttp&gt;

        &lt;cfif NOT FindNoCase(&quot;Auth=&quot;,cfhttp.filecontent)&gt;
            &lt;cfset loginAuth = &quot;Authorization Failed&quot; /&gt;
        &lt;cfelse&gt;
            &lt;cfset loginAuth = Mid(cfhttp.filecontent, FindNoCase(&quot;Auth=&quot;,cfhttp.filecontent) + (Len(&quot;Auth=&quot;)), Len(cfhttp.filecontent)) /&gt;
        &lt;/cfif&gt;
        &lt;!--- authToken in application var to prevent Google from sending captcha request (recommended by Google) ---&gt;
        &lt;cflock scope=&quot;application&quot; type=&quot;exclusive&quot; timeout=&quot;5&quot;&gt;
			&lt;cfset application.adw_loginAuth = loginAuth /&gt;
		&lt;/cflock&gt;
&lt;/cffunction&gt;
</pre>
<p>The Adwords API is called with an http post request to the appropriate service with the data request specified using SOAP. </p>
<pre class="brush: xml;">
&lt;cfsavecontent variable=&quot;CampaignRequestXML&quot;&gt;
&lt;soapenv:Envelope xmlns:soapenv=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot; xmlns=&quot;https://adwords.google.com/api/adwords/cm/v201003&quot;&gt;
	&lt;soapenv:Header&gt;
		&lt;RequestHeader&gt;
            &lt;authToken&gt;#application.adw_loginAuth#&lt;/authToken&gt;
            &lt;userAgent&gt;V2010 Get All Campaign Info&lt;/userAgent&gt;
            &lt;developerToken&gt;ADWORDS-API-DEV-TOKEN&lt;/developerToken&gt;
            &lt;clientEmail&gt;CLIENT-EMAIL&lt;/clientEmail&gt;
        &lt;/RequestHeader&gt;
    &lt;/soapenv:Header&gt;
    &lt;soapenv:Body&gt;
    	&lt;get&gt;
        	&lt;selector&gt;
            	&lt;ids&gt;&lt;/ids&gt;
					&lt;statsSelector&gt;
						&lt;dateRange&gt;
							&lt;min&gt;20100101&lt;/min&gt;
							&lt;max&gt;20100715&lt;/max&gt;
						&lt;/dateRange&gt;
                        &lt;startDate/&gt;
						&lt;endDate/&gt;
                        &lt;network&gt;ALL&lt;/network&gt;
						&lt;clicks/&gt;
						&lt;impressions/&gt;
					&lt;/statsSelector&gt;
            &lt;/selector&gt;
        &lt;/get&gt;
    &lt;/soapenv:Body&gt;
&lt;/soapenv:Envelope&gt;
&lt;/cfsavecontent&gt;
</pre>
<p>Clicks and impressions are obtained using the campaign service. Data returned from the Adwords API is also in the SOAP format. After stripping the prefixes out of the SOAP response that will prevent the XMLSearch function in ColdFusion from working as expected, the data can be extracted and stored in variables and displayed.</p>
<pre class="brush: coldfusion;">
&lt;!--- http SOAP request and xml parse ---&gt;
&lt;cfset CampaignResponseXML = adwordsSOAPresponse(CampaignRequestXML) /&gt;

&lt;cffunction name=&quot;adwordsSOAPresponse&quot; access=&quot;private&quot; returnType=&quot;string&quot;&gt;
	&lt;cfargument name=&quot;xmlSOAPrequest&quot; type=&quot;string&quot; required=&quot;yes&quot; default=&quot;&quot;&gt;

	&lt;cfif application.adw_loginAuth NEQ &quot;Authorization Failed&quot;&gt;
        &lt;cfhttp url=&quot;https://adwords.google.com/api/adwords/cm/v201003/CampaignService&quot; method=&quot;post&quot;&gt;
           &lt;cfhttpparam name=&quot;SOAPAction&quot; type=&quot;header&quot; value=&quot;&quot;/&gt;
           &lt;cfhttpparam type=&quot;xml&quot; value=&quot;#trim(arguments.xmlSOAPrequest)#&quot;/&gt;
        &lt;/cfhttp&gt;
        &lt;cfset responseXML = cfhttp.filecontent /&gt;
    &lt;cfelse&gt;
        &lt;p&gt;Google Authorization Failed.&lt;/p&gt;
        &lt;cfabort /&gt;
    &lt;/cfif&gt;

    &lt;!---remove soap: prefix or any other prefix from nodes that have it ---&gt;
    &lt;cfset responseXML = responseXML.ReplaceAll(&quot;(&lt;/?)(\w+:)&quot;,&quot;$1&quot;) /&gt;
    &lt;!--- remove xmlns: ---&gt;
    &lt;cfset responseXML = responseXML.ReplaceAll(&quot;xmlns(:\w+)?=&quot;&quot;[^&quot;&quot;]*&quot;&quot;&quot;,&quot;&quot;) /&gt;
    &lt;!--- remove xsi element prefixes ---&gt;
    &lt;cfset responseXML = responseXML.ReplaceAll('(/?)(xsi:)','$1') /&gt;

    &lt;cfreturn responseXML /&gt;
&lt;/cffunction&gt;
</pre>
<p>Now the data can be extracted to an array using XMLSearch. Then put into an array of structures to make it easy to dump.</p>
<pre class="brush: coldfusion;">
&lt;cfset CampaignResponseXML = adwordsSOAPresponse(CampaignRequestXML) /&gt;

&lt;cfset CampaignEntryNodes = XmlSearch(CampaignResponseXML, '//entries/') /&gt;

&lt;cfloop from=&quot;1&quot; to=&quot;#ArrayLen(CampaignEntryNodes)#&quot; index=&quot;num&quot;&gt;
	&lt;cfset entryStruct = StructNew() /&gt; 

    	&lt;cfset entryStruct.id = CampaignEntryNodes[num].id.XmlText /&gt;
        &lt;cfset entryStruct.name = CampaignEntryNodes[num].name.XmlText /&gt;
        &lt;cfset entryStruct.status = CampaignEntryNodes[num].status.XmlText /&gt;
        &lt;cfset entryStruct.clicks = CampaignEntryNodes[num].campaignStats.clicks.XmlText /&gt;
        &lt;cfset entryStruct.impressions = CampaignEntryNodes[num].campaignStats.impressions.XmlText /&gt;

		&lt;cfset totalClicks = totalClicks + CampaignEntryNodes[num].campaignStats.clicks.XmlText /&gt;
        &lt;cfset totalImpressions = totalImpressions + CampaignEntryNodes[num].campaignStats.impressions.XmlText /&gt;
        &lt;cfset arrayAppend(campaignStatsArray,duplicate(entryStruct)) /&gt;

&lt;/cfloop&gt;

&lt;cfdump var=&quot;#campaignStatsArray#&quot;&gt;
&lt;p&gt;Total clicks: #totalClicks#&lt;br /&gt;
Total Impressions: #totalImpressions#&lt;/p&gt;
</pre>
<p>Code in its entirety:</p>
<pre class="brush: coldfusion;">
&lt;!--- cfapplication is not needed if application.cfc exists ---&gt;
&lt;cfapplication name=&quot;adwordsapi&quot; applicationtimeout=&quot;#createtimespan(2,0,0,0)#&quot; /&gt;

&lt;cfset totalClicks = 0 /&gt;
&lt;cfset totalImpressions = 0 /&gt;
&lt;cfset campaignStatsArray = ArrayNew(1) /&gt;
&lt;cfset campaignID = &quot;&quot; /&gt;
&lt;cfset campaignStatusArray = ArrayNew(1) /&gt;
&lt;!---
	Adwords API parameters:
	Set email and password to adwords account
	Dev token is from MCC API details
---&gt;
&lt;cfscript&gt;
   api = structnew();
   api.email = &quot;GMAIL-ADDRESS-HERE&quot;;
   api.password = &quot;GMAIL-PASSWORD&quot;;
   api.devtoken = &quot;API-DEV-TOKEN&quot;;
   api.campaignService = &quot;https://adwords.google.com/api/adwords/cm/v201003/CampaignService&quot;;
   api.clientEmail = &quot;CLIENT-EMAIL-HERE&quot;;
   api.startDate = DateFormat(Now(), 'yyyymmdd');
   api.endDate = DateFormat(Now(), 'yyyymmdd');
&lt;/cfscript&gt;

&lt;cfif NOT StructKeyExists(application, &quot;adw_loginAuth&quot;)&gt;
	&lt;cfset googleLogin(api.email,api.password) /&gt;
&lt;/cfif&gt;

&lt;cffunction name=&quot;googleLogin&quot; access=&quot;private&quot; hint=&quot;GA account authorization&quot;&gt;
        &lt;cfargument name=&quot;email&quot; type=&quot;string&quot; required=&quot;yes&quot; default=&quot;&quot;&gt;
        &lt;cfargument name=&quot;password&quot; type=&quot;string&quot;required=&quot;yes&quot; default=&quot;&quot;&gt;
        &lt;cfargument name=&quot;gaLoginUrl&quot; type=&quot;string&quot; required=&quot;no&quot; default=&quot;https://www.google.com/accounts/ClientLogin&quot;&gt;

        &lt;cfset var loginAuth = &quot;&quot; /&gt;

        &lt;cfhttp url=&quot;#arguments.gaLoginUrl#&quot; method=&quot;post&quot;&gt;
            &lt;cfhttpparam name=&quot;accountType&quot; type=&quot;url&quot; value=&quot;GOOGLE&quot;&gt;
            &lt;cfhttpparam name=&quot;Email&quot; type=&quot;url&quot; value=&quot;#arguments.email#&quot;&gt;
            &lt;cfhttpparam name=&quot;Passwd&quot; type=&quot;url&quot; value=&quot;#arguments.password#&quot;&gt;
            &lt;cfhttpparam name=&quot;service&quot; type=&quot;url&quot; value=&quot;adwords&quot;&gt;
            &lt;cfhttpparam name=&quot;source&quot; type=&quot;url&quot; value=&quot;adwords-clicks-impressions&quot;&gt;
        &lt;/cfhttp&gt;

        &lt;cfif NOT FindNoCase(&quot;Auth=&quot;,cfhttp.filecontent)&gt;
            &lt;cfset loginAuth = &quot;Authorization Failed&quot; /&gt;
        &lt;cfelse&gt;
            &lt;cfset loginAuth = Mid(cfhttp.filecontent, FindNoCase(&quot;Auth=&quot;,cfhttp.filecontent) + (Len(&quot;Auth=&quot;)), Len(cfhttp.filecontent)) /&gt;
        &lt;/cfif&gt;
        &lt;!--- authToken in application var to prevent Google from sending captcha request (recommended by Google) ---&gt;
        &lt;cflock scope=&quot;application&quot; type=&quot;exclusive&quot; timeout=&quot;5&quot;&gt;
			&lt;cfset application.adw_loginAuth = loginAuth /&gt;
		&lt;/cflock&gt;
&lt;/cffunction&gt;

&lt;cffunction name=&quot;adwordsSOAPresponse&quot; access=&quot;private&quot; returnType=&quot;string&quot;&gt;
	&lt;cfargument name=&quot;xmlSOAPrequest&quot; type=&quot;string&quot; required=&quot;yes&quot; default=&quot;&quot;&gt;

	&lt;cfif application.adw_loginAuth NEQ &quot;Authorization Failed&quot;&gt;
        &lt;cfhttp url=&quot;#api.campaignService#&quot; method=&quot;post&quot;&gt;
           &lt;cfhttpparam name=&quot;SOAPAction&quot; type=&quot;header&quot; value=&quot;&quot;/&gt;
           &lt;cfhttpparam type=&quot;xml&quot; value=&quot;#trim(arguments.xmlSOAPrequest)#&quot;/&gt;
        &lt;/cfhttp&gt;
        &lt;cfset responseXML = cfhttp.filecontent /&gt;
    &lt;cfelse&gt;
        &lt;p&gt;Google Authorization Failed.&lt;/p&gt;
        &lt;cfabort /&gt;
    &lt;/cfif&gt;

    &lt;!---remove soap: prefix or any other prefix from nodes that have it ---&gt;
    &lt;cfset responseXML = responseXML.ReplaceAll(&quot;(&lt;/?)(\w+:)&quot;,&quot;$1&quot;) /&gt;
    &lt;!--- remove xmlns: ---&gt;
    &lt;cfset responseXML = responseXML.ReplaceAll(&quot;xmlns(:\w+)?=&quot;&quot;[^&quot;&quot;]*&quot;&quot;&quot;,&quot;&quot;) /&gt;
    &lt;!--- remove xsi element prefixes ---&gt;
    &lt;cfset responseXML = responseXML.ReplaceAll('(/?)(xsi:)','$1') /&gt;

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

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot; /&gt;
&lt;title&gt;Adwords API&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;cfoutput&gt;

&lt;!---Campaign Info ---&gt;
&lt;cfsavecontent variable=&quot;CampaignRequestXML&quot;&gt;
&lt;soapenv:Envelope xmlns:soapenv=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot; xmlns=&quot;https://adwords.google.com/api/adwords/cm/v201003&quot;&gt;
	&lt;soapenv:Header&gt;
		&lt;RequestHeader&gt;
            &lt;authToken&gt;#application.adw_loginAuth#&lt;/authToken&gt;
            &lt;userAgent&gt;V2010 Get All Campaign Info&lt;/userAgent&gt;
            &lt;developerToken&gt;#api.devtoken#&lt;/developerToken&gt;
            &lt;clientEmail&gt;#api.clientEmail#&lt;/clientEmail&gt;
        &lt;/RequestHeader&gt;
    &lt;/soapenv:Header&gt;
    &lt;soapenv:Body&gt;
    	&lt;get&gt;
        	&lt;selector&gt;
            	&lt;ids&gt;&lt;/ids&gt;
					&lt;statsSelector&gt;
						&lt;dateRange&gt;
							&lt;min&gt;#api.startDate#&lt;/min&gt;
							&lt;max&gt;#api.endDate#&lt;/max&gt;
						&lt;/dateRange&gt;
                        &lt;startDate/&gt;
						&lt;endDate/&gt;
                        &lt;network&gt;ALL&lt;/network&gt;
						&lt;clicks/&gt;
						&lt;impressions/&gt;
					&lt;/statsSelector&gt;
            &lt;/selector&gt;
        &lt;/get&gt;
    &lt;/soapenv:Body&gt;
&lt;/soapenv:Envelope&gt;
&lt;/cfsavecontent&gt;

&lt;!--- http SOAP request and xml parse ---&gt;
&lt;cfset CampaignResponseXML = adwordsSOAPresponse(CampaignRequestXML) /&gt;

&lt;cfset CampaignEntryNodes = XmlSearch(CampaignResponseXML, '//entries/') /&gt;

&lt;cfloop from=&quot;1&quot; to=&quot;#ArrayLen(CampaignEntryNodes)#&quot; index=&quot;num&quot;&gt;
	&lt;cfset entryStruct = StructNew() /&gt; 

    	&lt;cfset entryStruct.id = CampaignEntryNodes[num].id.XmlText /&gt;
        &lt;cfset entryStruct.name = CampaignEntryNodes[num].name.XmlText /&gt;
        &lt;cfset entryStruct.status = CampaignEntryNodes[num].status.XmlText /&gt;
        &lt;cfset entryStruct.clicks = CampaignEntryNodes[num].campaignStats.clicks.XmlText /&gt;
        &lt;cfset entryStruct.impressions = CampaignEntryNodes[num].campaignStats.impressions.XmlText /&gt;

		&lt;cfset totalClicks = totalClicks + CampaignEntryNodes[num].campaignStats.clicks.XmlText /&gt;
        &lt;cfset totalImpressions = totalImpressions + CampaignEntryNodes[num].campaignStats.impressions.XmlText /&gt;
        &lt;cfset arrayAppend(campaignStatsArray,duplicate(entryStruct)) /&gt;

&lt;/cfloop&gt;

&lt;cfdump var=&quot;#campaignStatsArray#&quot;&gt;
&lt;p&gt;Total clicks: #totalClicks#&lt;br /&gt;
Total Impressions: #totalImpressions#&lt;/p&gt;

&lt;/cfoutput&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<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/2010/07/18/clicks-and-impressions-from-google-adwords-api-using-coldfusion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google Analytics Data Export API with Google Chart Visualizations</title>
		<link>http://www.jensbits.com/2010/06/23/google-analytics-data-export-api-with-google-chart-visualizations-2/</link>
		<comments>http://www.jensbits.com/2010/06/23/google-analytics-data-export-api-with-google-chart-visualizations-2/#comments</comments>
		<pubDate>Wed, 23 Jun 2010 06:45:54 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[Google Analytics]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=769</guid>
		<description><![CDATA[You can punch into the Google Analytics Data Export API, pull out some stats, and stuff them into some nice graphical charts using Google Chart Visualizations. This demo is done in PHP. Authenticate the User The user can authenticate via the ClientLogin or using the AuthSub login which is actually more secure. For the ClientLogin, [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>You can punch into the Google Analytics Data Export API, pull out some stats, and stuff them into some nice graphical charts using Google Chart Visualizations. This demo is done in PHP.<br />
<img src="/images/googlechartviz.gif" alt="Google Chart Visualizations" /></p>
<h2>Authenticate the User</h2>
<p>The user can authenticate via the ClientLogin or using the AuthSub login which is actually more secure. For the ClientLogin, a typical username/password form is used. For the AuthSub login a link is used to send the user to Google to log in. Both are shown below. Normally you would use one or the other.</p>
<pre class="brush: php;">
&lt;form name=&quot;loginForm&quot; action=&quot;&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;&quot; method=&quot;post&quot;&gt;
		    &lt;label for=&quot;email&quot;&gt;Gmail:&lt;/label&gt;
		    &lt;input id=&quot;email&quot; type=&quot;text&quot; name=&quot;email&quot; /&gt;
		    &lt;label for=&quot;password&quot;&gt;Password:&lt;/label&gt;
		    &lt;input type=&quot;password&quot; name=&quot;password&quot; id=&quot;password&quot;/&gt;
		    &lt;br /&gt;&lt;br /&gt;
		    &lt;button type=&quot;submit&quot; id=&quot;submitLogin&quot;&gt;Submit&lt;/button&gt;
		&lt;/form&gt;
        &lt;p&gt;&lt;a class=&quot;button&quot; href=&quot;https://www.google.com/accounts/AuthSubRequest?next=http://www.jensbits.com/demos/ga/app/&amp;scope=https://www.google.com/analytics/feeds/&amp;secure=0&amp;session=1&quot;&gt;Or,authenticate using AuthSub through Google.&lt;/a&gt;&lt;/p&gt;
</pre>
<p>And, of course, the two authentication methods use different http calls to return a token that can be used to access the API.</p>
<pre class="brush: php;">
//ClientLogin: try to log in and get session token for multiple API calls
if(isset($_POST['email']) &amp;&amp; isset($_POST['password'])){
	$_SESSION['sessionToken'] = googleLogin($_POST['email'],$_POST['password']);
}
//AuthSub: exchange token for session token so multiple calls can be made to api
if(isset($_REQUEST['token'])){
	$_SESSION['authSub'] = true;
	$_SESSION['sessionToken'] = get_session_token($_REQUEST['token']);
}

//returns sessionToken for multiple calls to API
function googleLogin($email,$passwd){

    $clientlogin_url = &quot;https://www.google.com/accounts/ClientLogin&quot;;
     $clientlogin_post = array(
    &quot;accountType&quot; =&gt; &quot;GOOGLE&quot;,
    &quot;Email&quot; =&gt; $email,
    &quot;Passwd&quot; =&gt; $passwd,
    &quot;service&quot; =&gt; &quot;analytics&quot;,
    &quot;source&quot; =&gt; &quot;my-analytics&quot;
	);

	$curl = curl_init($clientlogin_url);

	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post);
	curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

	$response = curl_exec($curl);

	preg_match(&quot;/Auth=([a-z0-9_\-]+)/i&quot;, $response, $matches);
	$sessionToken = $matches[1];

	if (strlen($sessionToken) == 0){
		$sessionToken = &quot;Authentication Failed.&quot;;
	}

 	return $sessionToken;
}

//AuthSub returns session token for multiple calls to API
	function get_session_token($onetimetoken) {
		$output = call_api($onetimetoken, &quot;https://www.google.com/accounts/AuthSubSessionToken&quot;);

		if (preg_match(&quot;/Token=(.*)/&quot;, $output, $matches))
		{
			$sessionToken = $matches[1];
		} else {
			echo &quot;Error authenticating with Google.&quot;;
			exit;
		}

		return $sessionToken;
	}
</pre>
<h2>Data Requests</h2>
<p>Once authenticated to a Google Analytics account and a multi-use session token is acquired, the data requests can be made. The first one will request the profiles (websites) associated with the account. If there is more than one, a dropdown select is populated allowing for the selection of the profile from which to pull data.</p>
<pre class="brush: php;">
$accountxml = call_api($_SESSION['sessionToken'],&quot;https://www.google.com/analytics/feeds/accounts/default&quot;);
// Get an array with the available accounts
$profiles = parse_account_list($accountxml);
</pre>
<p>The call_api function is going to return the XML data from Google based on the request URL sent in. In this case, it is getting the profile data and the parse_account_list function is rolling through that XML and putting the profile data in an array.</p>
<pre class="brush: php;">
//gets the data
function call_api($sessionToken,$url){
	$curl = curl_init($url);

	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	if (isset($_SESSION['authSub'])){
		$curlheader[0] = sprintf(&quot;Authorization: AuthSub token=\&quot;%s\&quot;/n&quot;, $sessionToken);
	} else {
		$curlheader[0] = &quot;Authorization: GoogleLogin auth=&quot; . $sessionToken;
	}
	curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader);

	$response = curl_exec($curl);
	curl_close($curl);

	return $response;
}

//returns accounts list as array
function parse_account_list($xml){
	$doc = new DOMDocument();
	if(stripos($xml,&quot;&lt;&quot;) !== FALSE)
	{
		$doc-&gt;loadXML($xml);

		$entries = $doc-&gt;getElementsByTagName('entry');
		$i = 0;
		$profiles= array();
		foreach($entries as $entry)
		{
			$profiles[$i] = array();

			$title = $entry-&gt;getElementsByTagName('title');
			$profiles[$i][&quot;title&quot;] = $title-&gt;item(0)-&gt;nodeValue;

			$entryid = $entry-&gt;getElementsByTagName('id');
			$profiles[$i][&quot;entryid&quot;] = $entryid-&gt;item(0)-&gt;nodeValue;

			$tableId = $entry-&gt;getElementsByTagName('tableId');
			$profiles[$i][&quot;tableId&quot;] = $tableId-&gt;item(0)-&gt;nodeValue;

			$i++;
		}
		return $profiles;
	} else {
		$sessionToken = &quot;Authentication Failed.&quot;;
	}

}
</pre>
<p>The dropdown of the profile array:</p>
<pre class="brush: php;">
echo &quot;&lt;form name='siteSelect' id='siteSelect' method='post' action='&quot; . $_SERVER['PHP_SELF'] . &quot;'&gt;&lt;p&gt;&lt;label for='tableId'&gt;Select Site:&lt;/label&gt;&lt;select name='tableId' id='tableId'&gt;&quot;;
		foreach($profiles as $profile)
		{
			if($profile[&quot;tableId&quot;] == $table_Id)
				$selected = &quot;selected='selected'&quot;;
				echo &quot;&lt;option value='&quot; . $profile[&quot;tableId&quot;] . &quot;|&quot; . $profile[&quot;title&quot;] . &quot;'&quot; . $selected  . &quot;&gt;&quot; . $profile[&quot;title&quot;] . &quot;&lt;/option&gt;&quot;;
				$selected = &quot; &quot;;
		}
		echo &quot;&lt;/select&gt;&lt;/p&gt;&quot;;
</pre>
<p>The parse_data function below is going to roll through the data returned from Google Analytics and spit out an array that can be used to create the Google Visualization graphs.</p>
<pre class="brush: php;">
//returns data as array
function parse_data($xml){
		$doc = new DOMDocument();
		$doc-&gt;loadXML($xml);

		$entries = $doc-&gt;getElementsByTagName('entry');
		$i = 0;
		$results = array();
		foreach($entries as $entry)
		{
			$countries[$i] = array();

			$dimensions = $entry-&gt;getElementsByTagName('dimension');
			foreach($dimensions as $dimension)
			{
				$results[$i][ltrim($dimension-&gt;getAttribute(&quot;name&quot;),&quot;ga:&quot;)] =  $dimension-&gt;getAttribute('value');
			}

			$metrics = $entry-&gt;getElementsByTagName('metric');
			foreach($metrics as $metric)
			{
				$results[$i][ltrim($metric-&gt;getAttribute('name'),&quot;ga:&quot;)] =  $metric-&gt;getAttribute('value');
			}

			$i++;
		}
		return $results;
}
</pre>
<h2>Graph Generation</h2>
<p>Google Visualizations requires the inclusion of a javascript file in the head tag and empty div&#8217;s that will be the target for the graphs:</p>
<pre class="brush: xml;">
&lt;script type=&quot;text/javascript&quot; src=&quot;http://www.google.com/jsapi&quot;&gt;&lt;/script&gt;
</pre>
<p>The target div&#8217;s should be placed on the page where you want them to appear.</p>
<pre class="brush: xml;">
&lt;div id='barchart_div'&gt;&lt;/div&gt;
&lt;div id='piechart_div'&gt;&lt;/div&gt;
</pre>
<p>Finally, the data can be added to the chart generation javascript:</p>
<pre class="brush: jscript;">
&lt;script type=&quot;text/javascript&quot;&gt;
      google.load(&quot;visualization&quot;, &quot;1&quot;, {packages:[&quot;piechart&quot;]});
      google.setOnLoadCallback(drawPieChart);
      function drawPieChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Referrer');
        data.addColumn('number', 'Visits');
        data.addRows(&lt;?php echo sizeof($referrers) ?&gt;);
        &lt;?php
        $row = 0;
        foreach($referrers as $referrer)
		{
		?&gt;
		data.setValue(&lt;?php echo $row ?&gt;,0,'&lt;?php echo $referrer[&quot;source&quot;] ?&gt;');
		data.setValue(&lt;?php echo $row ?&gt;,1,&lt;?php echo $referrer[&quot;visits&quot;] ?&gt;);
		&lt;?php
		$row++;
		}
		?&gt;

        var chart = new google.visualization.PieChart(document.getElementById('piechart_div'));
        chart.draw(data, {width: 600, height: 440, is3D: true, title: 'Referrer/Visits'});
	  	}

	  google.load(&quot;visualization&quot;, &quot;1&quot;, {packages:[&quot;columnchart&quot;]});
      google.setOnLoadCallback(drawBarChart);
      function drawBarChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Day');
        data.addColumn('number', 'Visits');
        data.addRows(&lt;?php echo sizeof($visitsgraph) ?&gt;);
		&lt;?php
         $row = 0;
        foreach($visitsgraph as $visits)
		{
		?&gt;
		data.setValue(&lt;?php echo $row ?&gt;,0,'&lt;?php if ($visits_graph_type == &quot;month&quot;){echo date(&quot;M&quot;, mktime(0, 0, 0, $visits[&quot;month&quot;])).&quot; &quot;.$visits[&quot;year&quot;];}else{echo substr($visits['date'],6,2).&quot;-&quot;.date('M', mktime(0, 0, 0, substr($visits['date'],4,2))).&quot;-&quot;.substr($visits['date'],0,4);} ?&gt;');
		data.setValue(&lt;?php echo $row ?&gt;,1,&lt;?php echo $visits[&quot;visits&quot;] ?&gt;);
		&lt;?php
		$row++;
		}
		?&gt;
        var chart = new google.visualization.ColumnChart(document.getElementById('barchart_div'));
        chart.draw(data, {width: 700, height: 400, is3D: true, title: 'Visits'});
      }

    &lt;/script&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=0470413964" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe></p>
</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=0470529393" 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=0470562315" 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=0470531282" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
</div>
<p id="demo"><a href="/demos/ga/app/"><span>Demo</span></a></p>
<p id="download"><a href="/media/code/GAandGoogleCharts.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/2010/06/23/google-analytics-data-export-api-with-google-chart-visualizations-2/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<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>Generating Signatures in ColdFusion with RSA-SHA1 for Secure AuthSub in Google Analytics</title>
		<link>http://www.jensbits.com/2010/05/16/generating-signatures-in-coldfusion-with-rsa-sha1-for-secure-authsub-in-google-analytics/</link>
		<comments>http://www.jensbits.com/2010/05/16/generating-signatures-in-coldfusion-with-rsa-sha1-for-secure-authsub-in-google-analytics/#comments</comments>
		<pubDate>Sun, 16 May 2010 21:24:38 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[ColdFusion]]></category>
		<category><![CDATA[Google Analytics]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=726</guid>
		<description><![CDATA[To send secure AuthSub requests to Google Analytics, you have to sign the request with a private key that is verified against the certificate you upload to Google. Google has a library where this can be done in Java that is specific to Google Analytics and, provided you can add .jar files to your ColdFusion [...]


Related posts:<ol><li><a href='http://www.jensbits.com/2009/12/19/coldfusion-and-google-analytics-getting-out-what-you-put-in/' rel='bookmark' title='Permanent Link: ColdFusion and Google Analytics: Getting Out What You Put In'>ColdFusion and Google Analytics: Getting Out What You Put In</a></li>
<li><a href='http://www.jensbits.com/2009/05/02/hooking-into-google-analytics-with-coldfusion/' rel='bookmark' title='Permanent Link: Hooking into Google Analytics with ColdFusion'>Hooking into Google Analytics with ColdFusion</a></li>
<li><a href='http://www.jensbits.com/2009/05/10/google-analytics-api-login-authentication-with-coldfusion/' rel='bookmark' title='Permanent Link: Google Analytics API Login Authentication with ColdFusion'>Google Analytics API Login Authentication with ColdFusion</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>To send secure AuthSub requests to Google Analytics, you have to sign the request with a private key that is verified against the certificate you upload to Google. Google has a library where this can be done in Java that is specific to Google Analytics and, provided you can add .jar files to your ColdFusion server or use <a href="http://javaloader.riaforge.org/">javaloader</a>, you can run them using ColdFusion. If you need to roll your own or simply want to control the process, this example may help.</p>
<p>Before you implement any code that signs requests, the keys and certificate must be generated and then registered with Google you are attempting to access. Google has <a href="http://code.google.com/apis/gdata/docs/auth/authsub.html#Registered">instructions on how to generate the keys and certificate using OpenSSL</a> and <a href="http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html">how to register the certificate with Google</a>. You will need the private key in the PKCS#8 format.</p>
<p>Google also supplies <a href="http://code.google.com/apis/accounts/docs/AuthSub.html#signingrequests">instructions for signing the AuthSub requests</a> which is what we will step through here.</p>
<p>To get a single-use token for secure AuthSub, you send the user to authenticate through Google with a link similar to this:</p>
<pre class="brush: xml;">
&lt;a href=&quot;https://www.google.com/accounts/AuthSubRequest?next=YOUR_PAGE_HERE?secureAuth=yes&amp;scope=https://www.google.com/analytics/feeds/&amp;secure=1&amp;session=1&quot;&gt;Log in using Secure AuthSub through Google&lt;/a&gt;
</pre>
<p>Notice that secure is set to 1 indicating we want to send secure requests. Session is also set to 1 indicating we want a multi-use authorization token for multiple calls to the Google Analytics Data Export API. If you are only making one call to the API, you can set session to 0 (zero).</p>
<p>Google will then the user to your page designated by the next parameter with the token attached as a URL parameter called &#8220;token.&#8221; After getting this single-use token back from Google, you then need to send it back to Google to exchange for your multi-use token. This is where the signing begins. Every request from this point forward needs to be signed.</p>
<p>Secure AuthSub differs from AuthSub in that it requires several parameters to be added to the Authorization header of the request. They are:</p>
<ol>
<li>token: single-use token (or multi-use token once you get it) from Google</li>
<li>sigalg: rsa-sah1</li>
<li>data: the http-method, request URL, timestamp, and nonce all separated by a space.</li>
<li>sig: the signature made by the private key generated against the data parameter above.</li>
</ol>
<p>Generating this only requires a few lines of ColdFusion code:</p>
<pre class="brush: coldfusion;">
        &lt;cfset Math = createObject('java','java.lang.Math') /&gt;
        &lt;cfset randNum = createObject('java', 'java.security.SecureRandom') /&gt;
        &lt;cfset numeric_nonce = Math.abs(JavaCast(&quot;long&quot;,randNum.nextLong())) /&gt;
        &lt;cfset nonce = numeric_nonce.toString() /&gt;
        &lt;cfset timestmp = DateDiff(&quot;s&quot;,DateConvert(&quot;utc2Local&quot;, &quot;January 1 1970 00:00&quot;), Now()) /&gt;

        &lt;cfset appSignature = rsa_sha1(rsaPrivateKey, 'GET https://www.google.com/accounts/AuthSubSessionToken ' &amp; timestmp &amp; ' ' &amp; nonce) /&gt;

        &lt;cfset authHeaderValue = 'AuthSub token=&quot;' &amp; URL.token &amp; '&quot; data=&quot;GET https://www.google.com/accounts/AuthSubSessionToken ' &amp; timestmp &amp; ' ' &amp; nonce &amp; '&quot; sig=&quot;' &amp; appSignature &amp; '&quot;  sigalg=&quot;rsa-sha1&quot;' /&gt;
</pre>
<p>The rsa_sha1 function creates the signature. It was written by Sharad Gupta and used here with permission.</p>
<pre class="brush: coldfusion;">
&lt;cffunction name=&quot;rsa_sha1&quot; returntype=&quot;string&quot; access=&quot;public&quot; descrition=&quot;RSA-SHA1 computation based on supplied private key and supplied base signature string.&quot;&gt;
    &lt;!---Written by Sharad Gupta sharadg@gmail.com (used with permission)---&gt;
           &lt;cfargument name=&quot;signKey&quot; type=&quot;string&quot; required=&quot;true&quot; hint=&quot;base64 formatted PKCS8 private key&quot;&gt;
           &lt;cfargument name=&quot;signMessage&quot; type=&quot;string&quot; required=&quot;true&quot; hint=&quot;msg to sign&quot;&gt;
           &lt;cfargument name=&quot;sFormat&quot; type=&quot;string&quot; required=&quot;false&quot; default=&quot;UTF-8&quot;&gt;

           &lt;cfset var jKey = JavaCast(&quot;string&quot;, arguments.signKey)&gt;
           &lt;cfset var jMsg = JavaCast(&quot;string&quot;,arguments.signMessage).getBytes(arguments.sFormat)&gt;

           &lt;cfset var key = createObject(&quot;java&quot;, &quot;java.security.PrivateKey&quot;)&gt;
           &lt;cfset var keySpec = createObject(&quot;java&quot;,&quot;java.security.spec.PKCS8EncodedKeySpec&quot;)&gt;
           &lt;cfset var keyFactory = createObject(&quot;java&quot;,&quot;java.security.KeyFactory&quot;)&gt;
           &lt;cfset var b64dec = createObject(&quot;java&quot;, &quot;sun.misc.BASE64Decoder&quot;)&gt;

           &lt;cfset var sig = createObject(&quot;java&quot;, &quot;java.security.Signature&quot;)&gt;

           &lt;cfset var byteClass = createObject(&quot;java&quot;, &quot;java.lang.Class&quot;)&gt;
           &lt;cfset var byteArray = createObject(&quot;java&quot;,&quot;java.lang.reflect.Array&quot;)&gt;

           &lt;cfset byteClass = byteClass.forName(JavaCast(&quot;string&quot;,&quot;java.lang.Byte&quot;))&gt;
           &lt;cfset keyBytes = byteArray.newInstance(byteClass, JavaCast(&quot;int&quot;,&quot;1024&quot;))&gt;
           &lt;cfset keyBytes = b64dec.decodeBuffer(jKey)&gt;

           &lt;cfset sig = sig.getInstance(&quot;SHA1withRSA&quot;, &quot;SunJSSE&quot;)&gt;
           &lt;cfset sig.initSign(keyFactory.getInstance(&quot;RSA&quot;).generatePrivate(keySpec.init(keyBytes)))&gt;
           &lt;cfset sig.update(jMsg)&gt;
           &lt;cfset signBytes = sig.sign()&gt;

           &lt;cfreturn ToBase64(signBytes)&gt;
     &lt;/cffunction&gt;
</pre>
<p>The request for and parsing out of the multi-use token looks like this:</p>
<pre class="brush: coldfusion;">
&lt;cfhttp url=&quot;https://www.google.com/accounts/AuthSubSessionToken&quot; method=&quot;GET&quot;&gt;
 &lt;cfhttpparam name=&quot;Authorization&quot; type=&quot;header&quot; value=&quot;#authHeaderValue#&quot;&gt;
&lt;/cfhttp&gt;

&lt;cfset output = cfhttp.filecontent /&gt;

&lt;cfset authSubSessionToken = Mid(output, FindNoCase(&quot;Token=&quot;,output) + (Len(&quot;Token=&quot;)), Len(output)) /&gt;
</pre>
<p>Any more requests of the Data Export API have to be made in the same manner except now you will use the multi-use token (authSubSessionToken) as the token in the Authorization header.</p>
<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=032166034X" 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=0470529393" 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=0470562315" 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=0470531282" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
</div>
<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/19/coldfusion-and-google-analytics-getting-out-what-you-put-in/' rel='bookmark' title='Permanent Link: ColdFusion and Google Analytics: Getting Out What You Put In'>ColdFusion and Google Analytics: Getting Out What You Put In</a></li>
<li><a href='http://www.jensbits.com/2009/05/02/hooking-into-google-analytics-with-coldfusion/' rel='bookmark' title='Permanent Link: Hooking into Google Analytics with ColdFusion'>Hooking into Google Analytics with ColdFusion</a></li>
<li><a href='http://www.jensbits.com/2009/05/10/google-analytics-api-login-authentication-with-coldfusion/' rel='bookmark' title='Permanent Link: Google Analytics API Login Authentication with ColdFusion'>Google Analytics API Login Authentication with ColdFusion</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2010/05/16/generating-signatures-in-coldfusion-with-rsa-sha1-for-secure-authsub-in-google-analytics/feed/</wfw:commentRss>
		<slash:comments>1</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>CreateUserWizard Set Email as Username VB.NET 3.5</title>
		<link>http://www.jensbits.com/2010/03/05/createuserwizard-set-email-as-username-vb-net-3-5/</link>
		<comments>http://www.jensbits.com/2010/03/05/createuserwizard-set-email-as-username-vb-net-3-5/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 14:00:57 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[Work]]></category>

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


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

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

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

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

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


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2010/03/05/createuserwizard-set-email-as-username-vb-net-3-5/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
