SlideShare a Scribd company logo
1 of 4
Download to read offline
AutoCompleter Tutorial -
jQuery(Ajax)/PHP/MySQL
I thought i would write this tutorial because most of the auto completer applications i
have seen just dump the code into a zip and tell you how to use it rather than how and
why it works, knowing about this enables you to customise it a lot more (this has been
demonstrated with the other apps i have written here)!




And so we begin:
JavaScript

<script src="jquery-1.2.1.pack.js" type="text/javascript"></script><script
type="text/javascript">

function lookup(inputString) {
   if(inputString.length == 0) {
      // Hide the suggestion box.
      $(‘#suggestions’).hide();
   } else {
      $.post("rpc.php", {queryString: ""+inputString+""}, function(data){
         if(data.length >0) {
            $(‘#suggestions’).show();
            $(‘#autoSuggestionsList’).html(data);
         }
      });
   }
} // lookup

function fill(thisValue) {
   $(‘#inputString’).val(thisValue);
  $(‘#suggestions’).hide();
}

</script>

JS Explaniation

Ok, the above code it the guts to the script, this allows us to hook into the rpc.php file
which carries out all the processing.
The Lookup function takes the word from the input box and POSTS it to the rpc.php
page using the jQuery Ajax POST call.

IF the inputString is ‘0′ (Zero), it hides the suggestion box, naturally you would not
want this showing if there is nothing in the text box. to search for.

ELSE we take the ‘inputString’ and post it to the rpc.php page, the jQuery $.post()
function is used as follows…

$.post(url, [data], [callback])

The ‘callback’ part allows to hook in a function, this is where the real magic if thats
what you can call it happens.

IF the ‘data’ returned length is more than zero (ie: there is actually something to show),
show the suggestionBox and replace the HTML inside with the returned data.

SIMPLE!

Now for the PHP Backend (RPC.php)

As always my PHP Backend page is called rpc.php (Remote Procedure Call) not that it
actually does that, but hey-ho.

// PHP5 Implementation - uses MySQLi.
$db = new mysqli(‘localhost’, ‘root’ ,”, ‘autoComplete’);
if(!$db) {
   // Show error if we cannot connect.
   echo ‘ERROR: Could not connect to the database.’;
} else {
   // Is there a posted query string?
   if(isset($_POST[‘queryString’])) {
       $queryString = $_POST[‘queryString’];
       // Is the string length greater than 0?
       if(strlen($queryString) >0) {
       // Run the query: We use LIKE ‘$queryString%’
       // The percentage sign is a wild-card, in my example of countries it works like
this…
       // $queryString = ‘Uni’;
       // Returned data = ‘United States, United Kindom’;

    $query = $db->query("SELECT value FROM countries WHERE value LIKE
‘$queryString%’ LIMIT 10");
    if($query) {
       // While there are results loop through them - fetching an Object (i like PHP5
btw!).
       while ($result = $query ->fetch_object()) {
          // Format the results, im using <li> for the list, you can change it.
          // The onClick function fills the textbox with the result.
          echo ‘<li onclick="fill(’‘.$result->value.’‘);">’.$result->value.‘</li>’;
}
      } else {
         echo ‘ERROR: There was a problem with the query.’;
      }
   } else {
      // Dont do anything.
   } // There is a queryString.
} else {
   echo ‘There should be no direct access to this script!’;
}
}

?>

PHP Explaination

Im not going to go into much detail here because there are loads of comments in the
code above.

Basically, it takes the ‘QueryString’ and does a query with a wildcard at the en.

This means that in this case of the code each key-press generates a new query, this is
MySQL intensive if its always being done, but short of making it exceedingly complex
it is fine for small scale applications.

The PHP code is the part you have to change to work in your system, and all the it is
updating the ‘$query’ to your database, you should be able to see where you put the
table column name in etc…

CSS Styling - im using CSS3, YEA BABY! much easier although limits the
functionality to Firefox and Safari.

<style type="text/css">

.suggestionsBox {
   position: relative;
   left: 30px;
   margin: 10px 0px 0px 0px;
   width: 200px;
   background-color: #212427;
   -moz-border-radius: 7px;
   -webkit-border-radius: 7px;
   border: 2px solid #000;
   color: #fff;
}

.suggestionList {
   margin: 0px;
   padding: 0px;
}
.suggestionList li {
   margin: 0px 0px 3px 0px;
   padding: 3px;
   cursor: pointer;
}

.suggestionList li:hover {
   background-color: #659CD8;
}
</style>

The CSS is pretty standard, nothing out of the ordinary.

Main HTML

<div>

    <div>

   Type your county (for the demo):
<input size="30" id="inputString" onkeyup="lookup(this.value);" type="text" />

  </div>     <div class="suggestionsBox" id="suggestions" style="display: none;">

    <img src="upArrow.png" style="position: relative; top: -12px; left: 30px"
alt="upArrow" />

   <div class="suggestionList" id="autoSuggestionsList">

</div>

  </div>

</div>

That is the main bit of HTML, really all you need to run this is an input text box with
the ‘onkeyup’ function set to lookup(this.value); Also, i recommend NOT changing the
ID of the input box, unless you change it in the Javascript section

More Related Content

Recently uploaded

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

Featured

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Featured (20)

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 

AutoCompleter%20Tutorial

  • 1. AutoCompleter Tutorial - jQuery(Ajax)/PHP/MySQL I thought i would write this tutorial because most of the auto completer applications i have seen just dump the code into a zip and tell you how to use it rather than how and why it works, knowing about this enables you to customise it a lot more (this has been demonstrated with the other apps i have written here)! And so we begin: JavaScript <script src="jquery-1.2.1.pack.js" type="text/javascript"></script><script type="text/javascript"> function lookup(inputString) { if(inputString.length == 0) { // Hide the suggestion box. $(‘#suggestions’).hide(); } else { $.post("rpc.php", {queryString: ""+inputString+""}, function(data){ if(data.length >0) { $(‘#suggestions’).show(); $(‘#autoSuggestionsList’).html(data); } }); } } // lookup function fill(thisValue) { $(‘#inputString’).val(thisValue); $(‘#suggestions’).hide(); } </script> JS Explaniation Ok, the above code it the guts to the script, this allows us to hook into the rpc.php file which carries out all the processing.
  • 2. The Lookup function takes the word from the input box and POSTS it to the rpc.php page using the jQuery Ajax POST call. IF the inputString is ‘0′ (Zero), it hides the suggestion box, naturally you would not want this showing if there is nothing in the text box. to search for. ELSE we take the ‘inputString’ and post it to the rpc.php page, the jQuery $.post() function is used as follows… $.post(url, [data], [callback]) The ‘callback’ part allows to hook in a function, this is where the real magic if thats what you can call it happens. IF the ‘data’ returned length is more than zero (ie: there is actually something to show), show the suggestionBox and replace the HTML inside with the returned data. SIMPLE! Now for the PHP Backend (RPC.php) As always my PHP Backend page is called rpc.php (Remote Procedure Call) not that it actually does that, but hey-ho. // PHP5 Implementation - uses MySQLi. $db = new mysqli(‘localhost’, ‘root’ ,”, ‘autoComplete’); if(!$db) { // Show error if we cannot connect. echo ‘ERROR: Could not connect to the database.’; } else { // Is there a posted query string? if(isset($_POST[‘queryString’])) { $queryString = $_POST[‘queryString’]; // Is the string length greater than 0? if(strlen($queryString) >0) { // Run the query: We use LIKE ‘$queryString%’ // The percentage sign is a wild-card, in my example of countries it works like this… // $queryString = ‘Uni’; // Returned data = ‘United States, United Kindom’; $query = $db->query("SELECT value FROM countries WHERE value LIKE ‘$queryString%’ LIMIT 10"); if($query) { // While there are results loop through them - fetching an Object (i like PHP5 btw!). while ($result = $query ->fetch_object()) { // Format the results, im using <li> for the list, you can change it. // The onClick function fills the textbox with the result. echo ‘<li onclick="fill(’‘.$result->value.’‘);">’.$result->value.‘</li>’;
  • 3. } } else { echo ‘ERROR: There was a problem with the query.’; } } else { // Dont do anything. } // There is a queryString. } else { echo ‘There should be no direct access to this script!’; } } ?> PHP Explaination Im not going to go into much detail here because there are loads of comments in the code above. Basically, it takes the ‘QueryString’ and does a query with a wildcard at the en. This means that in this case of the code each key-press generates a new query, this is MySQL intensive if its always being done, but short of making it exceedingly complex it is fine for small scale applications. The PHP code is the part you have to change to work in your system, and all the it is updating the ‘$query’ to your database, you should be able to see where you put the table column name in etc… CSS Styling - im using CSS3, YEA BABY! much easier although limits the functionality to Firefox and Safari. <style type="text/css"> .suggestionsBox { position: relative; left: 30px; margin: 10px 0px 0px 0px; width: 200px; background-color: #212427; -moz-border-radius: 7px; -webkit-border-radius: 7px; border: 2px solid #000; color: #fff; } .suggestionList { margin: 0px; padding: 0px; }
  • 4. .suggestionList li { margin: 0px 0px 3px 0px; padding: 3px; cursor: pointer; } .suggestionList li:hover { background-color: #659CD8; } </style> The CSS is pretty standard, nothing out of the ordinary. Main HTML <div> <div> Type your county (for the demo): <input size="30" id="inputString" onkeyup="lookup(this.value);" type="text" /> </div> <div class="suggestionsBox" id="suggestions" style="display: none;"> <img src="upArrow.png" style="position: relative; top: -12px; left: 30px" alt="upArrow" /> <div class="suggestionList" id="autoSuggestionsList"> </div> </div> </div> That is the main bit of HTML, really all you need to run this is an input text box with the ‘onkeyup’ function set to lookup(this.value); Also, i recommend NOT changing the ID of the input box, unless you change it in the Javascript section