NO MORE CAREER
POLITICIANS!
Get Out Of Our House: Replacing congress with TRUE citizens!
Contact Doug!
Learn About Doug!
View Doug Boude's online resume
updated 11/18/2009

View Doug Boude's profile on LinkedIn
Link to me!

Follow Doug Boude on Twitter
Follow me!

Be Doug's friend on Facebook
Befriend me!
(I promise not to follow you home)
OO Lexicon
Chat with Doug!
Recent Entries
You may also be interested in...
Web Hosting

best web hosting - top web hosting sites, thetop10bestwebhosting.com

Czech your Page Rank!
Check Page Rank of any web site pages instantly:
This free page rank checking tool is powered by Page Rank Checker service
Surf's Up!
Visit Egosurf.org and massage YOUR web ego!
My Score: 9,001
Doug's Books

Read (and recommend)

  • Men are from Mars, Women are from Venus
  • The Wisdom of Crowds: Why the Many Are Smarter Than the Few and How Collective Wisdom Shapes Business, Economies, Societies and Nations
  • Blink: The Power of Thinking Without Thinking
  • Head First Design Patterns
  • Transact-SQL Programming
  • What's So Amazing About Grace?
  • Just So Stories (Rudyard Kipling collection)

Reading

  • Prayer: Does it Make Any Difference?
  • Data Mining (Practical Machine Learning Tools and Techniques)
<< September, 2010 >>
SMTWTFS
1234
567891011
12131415161718
19202122232425
2627282930
Search Blog

Recent Comments
Re: Railo 3.1 on Windows Server 2008 and IIS7 - Part 3 of 3 (by Jon at 8/27 2:04 PM)
Re: Hosts File Changes Not Acknowledged on Vista 64 (by Spacy at 8/24 3:46 PM)
Re: THE DAY CFUNITED DIED (by ComboFusion at 8/23 10:50 AM)
Re: My Grandpa (by Tasha at 8/10 4:29 PM)
Re: Just What IS a 'Service Layer', Anyway? (by dougboude at 8/02 10:10 AM)
Re: Just What IS a 'Service Layer', Anyway? (by Isaac at 8/02 2:25 AM)
Re: PayPal IPN Coldfusion CFC (by Soyestudiambre at 7/25 6:12 PM)
Re: PHP vs COLDFUSION (by Tony Garcia at 7/17 11:24 AM)
Re: PHP vs COLDFUSION (by dougboude at 7/14 8:45 AM)
Re: PHP vs COLDFUSION (by Lola LB at 7/14 5:51 AM)
Categories
Archives
Photo Albums
Funnies (5)
Family (3)
RSS

Powered by
BlogCFM v1.11

20 May 2009
Basic Ajax Select List Filter in PHP

I am a ColdFusion guy, without a doubt. At my new job, however, I have inherited the maintenance and enhancement duties of a large PHP application as well. One of the enhancements I was asked to make was to produce a select list of names that could be filtered on the fly as the user typed into a text box. Being somewhat new to PHP and having had to figure out a good approach to creating this feature, I thought I'd share it in case it helps someone else.

Picture if you will, a select list filled with names and immediately below it a text box for filtering that list. Better yet, here's what mine looks like:

 select list with ajax name filter


As the user begins typing in the text box, the select list begins to be filtered, re-filtering as each letter is added or removed.

I'm using the Prototype javascript library to perform the ajax calls, and a PHP script I call "adminAjax.php" that listens for and responds to those ajax calls. First off then, the HTML and JS that sets up the user interface:

<div id="namelist" name="namelist" style="height:350px;width:200px;"></div>
<div>
 Last Name: <input type="text" id="fltName" name="fltName" size="25" />
</div>

<script>
 Event.observe(window, 'load', function() {
  Event.observe('fltName', 'keyup', function(e){filterByName(e);});
  filterByName('');//this initially populates the select list with ALL names...
 });
</script>

 

basically, I have one div that will hold the select list ("namelist"), and some js that, on page load, will bind the 'filterByName' function to the keyup event on the 'fltName' textbox. So, with every character entered or removed from that textbox, the current value will be passed to the filterByName function. Here's the filterByName function:

function filterByName(strname){
 var params = new Hash();
 params.set('namestring',strname);
 params.set('actionval','getSelect');
 new Ajax.Updater('namelist','adminAjax.php',{parameters:params,method:'get'});
}

 

Okay, now on to adminAjax.php.

I'm using this template exclusively for ajax responses, so what I did was to create a switch/case statement that routes to the appropriate function based on the incoming 'actionval' parameter. Important to note: in my case, I chose to create the entire select list on this end and then return the completed HTML. The Updater that made the Ajax call will then place the returned HTML into the target div for us. Here's the code:

<?
 //make sure we have a default value for the actionval parameter...
 if(!isset($_GET['actionval'])){$_GET['actionval']='none';}
 
 switch ($_GET['actionval']){
  case 'getSelect':
   $retval = getSelect();
   echo $retval;
   break;
  case 'some_other_action':
   $retval = bogusCall($_GET['someParam']);
   echo $retval;
   break;
 }

 //end of our switch router! Now for the functions that feed it...

 function getSelect(){
  include("settings.php");
  $Query = "SELECT userid,firstname,lastname from myTable ";
  $Query .= " where firstname <> '' and lastname <> '' ";
  
  //filtering on lastname/firstname...?
  if(isset($_GET['namestring']) && strlen($_GET['namestring'])>0){
   $aStr = split(",",$_GET['namestring']);
   $len = strlen(trim($aStr[0]));
   $flen = (count($aStr) > 1)?strlen(trim($aStr[1])):0;
   $Query .= "AND SUBSTR(lastname,1,".$len.") = '".trim($aStr[0])."' ";
   if($flen > 0){
    $Query .= "AND SUBSTR(firstname,1,".$flen.") = '".trim($aStr[1])."' ";
   }
  }
  $Query .= "order by lastname,firstname";

         $Result=mysql_db_query($DBName,$Query,$Link);

         if(mysql_numrows($Result) == 0){
          $strField = "<br><br>No Records Found. Please Change Filter Values and Try Again.";
         } else {//we have some records...let's build the select list HTML.
   $strField ='<select name="selUsers" id="selUsers" size="20" style="width:200px;" >';
   while($row = mysql_fetch_assoc($Result)){
    $strField .= '<option value=\''.$row['userid'].'\'>'.$row['lastname'].', '.$row['firstname'].'</option>';
   }
   $strField .='</select>';
         }
         mysql_close();
  return $strField;  
 }

That's it!

You may be thinking what I was originally thinking, something along the lines of "wouldn't it just be faster to have given the page a json representation of all the names, then used JS to filter it on the client side?" Well, the answer (at least in my case) is NOPE. I am working with about 3,000 names, and my first approach was to do it using the JSON data. This worked fine in Firefox, but IE...of course it ran painfully slow. Using the Ajax approach and just creating a new select list as the filter value changes works surprisingly fast in all browsers!

Hope this helps.

If you would like a good set of starter snippets, you can grab the zip file here.

 

 




Posted by dougboude at 2:02 PM | PRINT THIS POST! |Link | 1 comment
Subscription Options

You are not logged in, so your subscription status for this entry is unknown. You can login or register here.

Re: Basic Ajax Select List Filter in PHP
Hi !

You can read my post on my website to get a working example of 3 linked list with Ajax : http://www.vincentroye.com/?p=339
Continent -> Country -> City
Easy and intuitive ;)

Cheers,

Vincent Roye.
Posted by Vincent Roye on April 28, 2010 at 12:37 AM

Name:   Required
Email:   Required your email address will not be publicly displayed.

Want to receive notifications when new comments are added? Login/Register for an account.

Time to take the Turing Test!!!

2 plus 10 equals
Type in the answer to the question you see above:

Your comment:

Sorry, no HTML allowed!