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

<channel>
	<title>jensbits.com &#187; php</title>
	<atom:link href="http://www.jensbits.com/tag/php/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>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>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>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.ajax and jQuery.post Form Submit Examples with PHP</title>
		<link>http://www.jensbits.com/2009/10/04/jquery-ajax-and-jquery-post-form-submit-examples-with-php/</link>
		<comments>http://www.jensbits.com/2009/10/04/jquery-ajax-and-jquery-post-form-submit-examples-with-php/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 00:11:55 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[jquery]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[forms]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=425</guid>
		<description><![CDATA[For a version of this using ColdFusion, see the CF jquery form submit post. Two jQuery functions that allow for the submission of form are the jQuery.ajax function and the jQuery.post function (there is also jQuery.get but that is not addressed here). More functionality, along with more complexity, is offered with the .ajax function while [...]


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/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>
<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>
</ol>]]></description>
			<content:encoded><![CDATA[<blockquote><p>For a version of this using ColdFusion, see the <a href="/2009/10/23/jquery-ajax-and-jquery-post-form-submit-examples-with-coldfusion/">CF jquery form submit post</a>.</p></blockquote>
<p>Two jQuery functions that allow for the submission of form are the jQuery.ajax function and the jQuery.post function (there is also jQuery.get but that is not addressed here). </p>
<p>More functionality, along with more complexity, is offered with the .ajax function while the .post function, with its more simple functionality and implementation, will be all that is needed for simple form posts.</p>
<blockquote><p>It is <strong>highly recommended</strong> that you get a tool like <a href="http://getfirebug.com/">Firebug</a> to see the post response coming back from the page. It helps immensely.</p></blockquote>
<p>Here is an example of both in action doing the same thing: form submit with email validation.</p>
<h2>jQuery.ajax</h2>
<p> The form:</p>
<pre class="brush: xml;">
&lt;form id=&quot;JqAjaxForm&quot;&gt;
&lt;fieldset&gt;
&lt;legend&gt;jQuery.ajax Form Submit&lt;/legend&gt;
&lt;p&gt;&lt;label for=&quot;name_ajax&quot;&gt;Name:&lt;/label&gt;&lt;br /&gt;
&lt;input id=&quot;name_ajax&quot; type=&quot;text&quot; name=&quot;name_ajax&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;label for=&quot;email_ajax&quot;&gt;E-mail:&lt;/label&gt;&lt;br /&gt;
&lt;input id=&quot;email_ajax&quot; type=&quot;text&quot; name=&quot;email_ajax&quot;  /&gt;&lt;/p&gt;
&lt;p&gt;&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;&lt;/p&gt;
&lt;/fieldset&gt;
&lt;/form&gt;
&lt;div id=&quot;message_ajax&quot;&gt;&lt;/div&gt;
</pre>
<p>Pretty simple, nothing fancy. There is a form for each jQuery function, .ajax and .post. The only difference in the forms are the element names.</p>
<p>jQuery controls the submit for the forms. For the .ajax submission the jQuery is this:</p>
<pre class="brush: jscript;">
$(function(){
    $(&quot;#JqAjaxForm&quot;).submit(function(){
        dataString = $(&quot;#JqAjaxForm&quot;).serialize();

        $.ajax({
        type: &quot;POST&quot;,
        url: &quot;process_form.php&quot;,
        data: dataString,
        dataType: &quot;json&quot;,
        success: function(data) {

            if(data.email_check == &quot;invalid&quot;){
                $(&quot;#message_ajax&quot;).html(&quot;&lt;div class='errorMessage'&gt;Sorry &quot; + data.name + &quot;, &quot; + data.email + &quot; is NOT a valid e-mail address. Try again.&lt;/div&gt;&quot;);
            } else {
                $(&quot;#message_ajax&quot;).html(&quot;&lt;div class='successMessage'&gt;&quot; + data.email + &quot; is a valid e-mail address. Thank you, &quot; + data.name + &quot;.&lt;/div&gt;&quot;);
            }

        }

        });

        return false;            

    });
});
</pre>
<p>The .serialize function is used to put the form data in a format that can be processed by a page on the server. The .ajax function options include:</p>
<ul>
<li>type: &#8220;get&#8221; or &#8220;post&#8221;</li>
<li>url: the page to receive the form data</li>
<li>data: the form data itself</li>
<li>dataType: the data type the function should expect back from the server</li>
<li>success function: runs on a succesful post to the page</li>
</ul>
<p>More information on the options and further explanations of the options used here can be found on the<a href="http://docs.jquery.com/Ajax/jQuery.ajax"> jQuery.ajax documentation page</a>.</p>
<h2>jQuery.post</h2>
<p>As in the .ajax example, the form is simple, only the names have been changed:</p>
<pre class="brush: xml;">
&lt;form id=&quot;JqPostForm&quot;&gt;
&lt;fieldset&gt;
&lt;legend&gt;jQuery.post Form Submit&lt;/legend&gt;
&lt;p&gt;&lt;label for=&quot;name_post&quot;&gt;Name:&lt;/label&gt;&lt;br /&gt;
&lt;input id=&quot;name_post&quot; type=&quot;text&quot; name=&quot;name_post&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;label for=&quot;email_post&quot;&gt;E-mail:&lt;/label&gt;&lt;br /&gt;
&lt;input id=&quot;email_post&quot; type=&quot;text&quot; name=&quot;email_post&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;&lt;/p&gt;
&lt;/fieldset&gt;
&lt;/form&gt;
&lt;div id=&quot;message_post&quot;&gt;&lt;/div&gt;
</pre>
<p>And again, jQuery controls the submit for the forms. For the .post submission the jQuery is this:</p>
<pre class="brush: jscript;">
$(function(){
    $(&quot;#JqPostForm&quot;).submit(function(){
        $.post(&quot;process_form.php&quot;, $(&quot;#JqPostForm&quot;).serialize(),
        function(data){
            if(data.email_check == 'invalid'){

                    $(&quot;#message_post&quot;).html(&quot;&lt;div class='errorMessage'&gt;Sorry &quot; + data.name + &quot;, &quot; + data.email + &quot; is NOT a valid e-mail address. Try again.&lt;/div&gt;&quot;);
            } else {
                $(&quot;#message_post&quot;).html(&quot;&lt;div class='successMessage'&gt;&quot; + data.email + &quot; is a valid e-mail address. Thank you, &quot; + data.name + &quot;.&lt;/div&gt;&quot;);
                }
        }, &quot;json&quot;);

        return false;

    });
});
</pre>
<p>jQuery.post is a shorter, easier way to post the form data. The function arguments are:</p>
<ul>
<li>url of the form processing page</li>
<li>the form data</li>
<li>the callback function
<li>
<li>the data type of the return data</li>
</ul>
<p>More information can be found on the<a href="http://docs.jquery.com/Ajax/jQuery.post"> jQuery.post documentation page</a>.</p>
<h2>Processing the Form</h2>
<p>Both methods are processed by the same page. It processes the form data, process_form.php in this example, by checking to see if the e-mail submitted is valid. Much more than that could be done on the page if needed.</p>
<pre class="brush: php;">
$email_check = '';
$return_json = '';

function isValidEmail($email){
    return eregi(&quot;^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$&quot;, $email);
}

if(isValidEmail($_POST['email_ajax']) || isValidEmail($_POST['email_post'])) {
   $email_check = 'valid';
}
else {
    $email_check = 'invalid';
}

$return_json = '{&quot;email_check&quot;:&quot;' . $email_check . '&quot;,';

if (isset($_POST['email_ajax'])){
    $return_json = $return_json . '&quot;name&quot;:&quot;' . $_POST['name_ajax'] . '&quot;,';
    $return_json = $return_json . '&quot;email&quot;:&quot;' . $_POST['email_ajax'] . '&quot;}';
} else {
    $return_json = $return_json . '&quot;name&quot;:&quot;' . $_POST['name_post'] . '&quot;,';
    $return_json = $return_json . '&quot;email&quot;:&quot;' . $_POST['email_post'] . '&quot;}';
}

echo $return_json;
</pre>
<p>This code puts the results of the e-mail validation and the form data in a <a href="http://json.org/">JSON-formatted</a> string. It then will echo the return data string which is picked up by the success function in the .ajax function or the function(data) function in the .post function on the original page. </p>
<p>I prefer working with JSON, but there are other options for the return data. Check the jQuery documentation for the types available to you.</p>
<p>The JSON response will look like this:</p>
<pre class="brush: jscript;">
{&quot;email_check&quot;:&quot;valid&quot;,&quot;name&quot;:&quot;Julia&quot;,&quot;email&quot;:&quot;julia@example.com&quot;}
</pre>
<p><span style="color: red;font-weight: bold;">NOTE: If you have PHP 5.2 or better and the <a href="http://us3.php.net/filter_var">filter_var</a> and <a href="http://us3.php.net/json_encode">json_encode</a> functions available, use the following code instead:</span></p>
<pre class="brush: php;">
$email_check = '';
$return_arr = array();

if(filter_var($_POST['email_ajax'], FILTER_VALIDATE_EMAIL) || filter_var($_POST['email_post'], FILTER_VALIDATE_EMAIL)) {
   $email_check = 'valid';
}
else {
    $email_check = 'invalid';
}

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

if (isset($_POST['email_ajax'])){
    $return_arr[&quot;name&quot;] = $_POST['name_ajax'];
    $return_arr[&quot;email&quot;] = $_POST['email_ajax'];
} else {
    $return_arr[&quot;name&quot;] = $_POST['name_post'];
    $return_arr[&quot;email&quot;] = $_POST['email_post'];

}

echo json_encode($return_arr);
</pre>
<p>The appropriate message based on the e-mail validation check is then displayed.</p>
<p>Pretty simple, pretty handy couple of jQuery functions. Once you see it in action, you get the idea.</p>
<p>Usual recommended jQuery and PHP reading:</p>
<div style="height: 250px;">
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847196705" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0321647491" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847195121" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0764557467" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
</div>
<p id="demo"><a href="/demos/jqsubmit/index.php"><span>Demo</span></a></p>
<p id="download"><a href="/media/code/jQAjaxPostPHP.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/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/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>
<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>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2009/10/04/jquery-ajax-and-jquery-post-form-submit-examples-with-php/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Session Timeout Warning PHP Example with jQuery/JS</title>
		<link>http://www.jensbits.com/2009/09/07/session-timeout-warning-php-example-with-jqueryjs/</link>
		<comments>http://www.jensbits.com/2009/09/07/session-timeout-warning-php-example-with-jqueryjs/#comments</comments>
		<pubDate>Tue, 08 Sep 2009 00:45:37 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[Web development]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[browser]]></category>

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


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

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

//Your timing variables in number of seconds

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

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

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

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

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

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

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

	//event create countdown ticker variable declaration
	var countdownTickerEvent; 	

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

	timeDifference = timeNow - pageRequestTime;

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

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

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

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

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

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

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

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

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

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

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



<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.jensbits.com/2009/09/07/session-timeout-warning-php-example-with-jqueryjs/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>jQuery Selection and Targeting of Dynamic ID Attributes</title>
		<link>http://www.jensbits.com/2009/05/17/jquery-selection-and-targeting-of-dynamic-id-attributes/</link>
		<comments>http://www.jensbits.com/2009/05/17/jquery-selection-and-targeting-of-dynamic-id-attributes/#comments</comments>
		<pubDate>Mon, 18 May 2009 00:12:09 +0000</pubDate>
		<dc:creator>jen</dc:creator>
				<category><![CDATA[Web development]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.jensbits.com/?p=170</guid>
		<description><![CDATA[When you have dynamically generated page content, either pulled from a database or otherwise generated on the fly, there are times when you need to target these areas with jQuery. For this example, six rows of radio buttons for a form are created using a PHP loop. Each unique id is created by concatenating a [...]


Related posts:<ol><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>When you have dynamically generated page content, either pulled from a database or otherwise generated on the fly, there are times when you need to target these areas with jQuery.</p>
<p>For this example, six rows of radio buttons for a form are created using a PHP loop. Each unique id is created by concatenating a predefined prefix with a number. It starts at 7 just to be different.</p>
<pre class="brush: php;">&lt;?php
 for($count = 7; $count &lt;= 12; $count += 1){

  echo &quot;&lt;tr id='row_$count'&gt;&quot;;
  echo &quot;&lt;td&gt;&lt;input id='radioA_$count' name='radio_$count' type='radio' value='1'&quot;;
  if(@$_POST['radio_'.$count]==1){ echo &quot; checked &quot;; }
  echo &quot;/&gt;&lt;/td&gt;&quot;;
  echo &quot;&lt;td&gt;&lt;input id='radioB_$count' name='radio_$count' type='radio' value='2'&quot;;
  if(@$_POST['radio_'.$count]==2){ echo &quot; checked &quot;; }
  echo &quot;/&gt;&lt;/td&gt;&quot;;
  echo &quot;&lt;td&gt;&lt;input id='radioC_$count' name='radio_$count' type='radio' value='3'&quot;;
  if(@$_POST['radio_'.$count]==3){ echo &quot; checked &quot;; }
  echo &quot;/&gt;&lt;/td&gt;&quot;;
  echo &quot;&lt;td&gt;&lt;input id='radioD_$count' name='radio_$count' type='radio' value='4'&quot;;
  if(@$_POST['radio_'.$count]==4){ echo &quot; checked &quot;; }
  echo &quot;/&gt;&lt;/td&gt;&lt;/tr&gt;&quot;;
 }
?&gt;</pre>
<p> jQuery will replace all selected radio buttons with an image on submit. To pull this off, the following information is needed:</p>
<ul>
<li>the number of rows (this is a table for a quickie example)</li>
<li>the first radio button number</li>
<li>the last radio button number</li>
</ul>
<p>Each row is numbered dynamically by concatenating the count number with the &#8216;row_&#8217; prefix string.</p>
<pre class="brush: xml;">&lt;tr id='row_$count'&gt;</pre>
<p>Each radio button has a dynamically generated id and name created in a similar fashion as the row.</p>
<pre class="brush: xml;">&lt;input id='radioA_$count' name='radio_$count' type='radio' value='1' /&gt;</pre>
<p>To get the number of rows, the jQuery size function is used. Count (get size) of ids that begin with &#8216;row_&#8217;. The &#8216;^&#8217; character means &#8216;begins with&#8217;.</p>
<pre class="brush: jscript;">var itemCount = $('[id^=row_]').size();</pre>
<p>To get the first radio button number, grab the number associated with the first row. It may not always be 1. The demo begins at 7 and ends at 12 to show you don&#8217;t, and sometimes won&#8217;t, always start at 1. First, where the id begins with &#8216;row&#8217;, get the first by using filter(&#8216;:first&#8217;) and its value of the id attribute by using attr(&#8216;id&#8217;).</p>
<pre class="brush: jscript;">var firstItem = $('[id^=row_]').filter(':first').attr('id');</pre>
<p>Next, the &#8216;row_&#8217; prefix is pulled off and the remaining substring is the number. The prefix &#8216;row_&#8217; is put in a variable. Then the prefix is pulled off leaving the number as a substring.</p>
<pre class="brush: jscript;">var firstItemPrefix = 'row_';
var firstItemNum = firstItem.substring((firstItemPrefix.length));</pre>
<p>Getting the number of the last item is easy. Just add the total number of items to the firstItemNum and subtract 1.</p>
<pre class="brush: jscript;">var lastItemNum = (parseInt(itemCount) + parseInt(firstItemNum)) - 1;</pre>
<p>Image replacement magic happens when a for loop rolls over the radio buttons and swaps out the selected ones for an image. If the radio button is checked, put the image after it and remove the radio button.</p>
<pre class="brush: jscript;">for(var i=firstItemNum; i &lt;= lastItemNum; i++)
    {
        if( $('#radioA_' + i).attr('checked') ) $('#radioA_' + i).after('&lt;img src=&quot;img/chk_black.gif&quot; /&gt;').remove();
        if( $('#radioB_' + i).attr('checked') ) $('#radioB_' + i).after('&lt;img src=&quot;img/chk_blue.gif&quot; /&gt;').remove();
        if( $('#radioC_' + i).attr('checked') ) $('#radioC_' + i).after('&lt;img src=&quot;img/chk_green.gif&quot; /&gt;').remove();
        if( $('#radioD_' + i).attr('checked') ) $('#radioD_' + i).after('&lt;img src=&quot;img/star.gif&quot; /&gt;').remove();
    }
</pre>
<p>I use this on a larger scale for paginated results from a database. For the demo, the results are not stored in a database so each time you hit submit, it only replaces the ones you just checked.</p>
<p>Recommended jQuery and PHP reading:</p>
<div style="height: 250px;">
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847196705" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=0321647491" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;margin-right: 25px">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=jensbits-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=1847195121" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<div style="float:left;">
<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=1590598628" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
</div>
<p id="demo"><a class="thickbox" href="/demos/jqdynamicselect/?KeepAlive=true&#038;TB_iframe=true&#038;height=250&#038;width=425"><span>View demo</span></a></p>
<p id="download"><a href="/demos/jqdynamicselect/jqdynamicselect.txt"><span>Download code</span></a></p>


<p>Related posts:<ol><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/2009/05/17/jquery-selection-and-targeting-of-dynamic-id-attributes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
