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

Viewers also liked

An%20Intermediate%20Google%20SketchUp%20Tutorial%20-%20Part%203
An%20Intermediate%20Google%20SketchUp%20Tutorial%20-%20Part%203An%20Intermediate%20Google%20SketchUp%20Tutorial%20-%20Part%203
An%20Intermediate%20Google%20SketchUp%20Tutorial%20-%20Part%203tutorialsruby
 
由一个简单的程序谈起--之一
由一个简单的程序谈起--之一由一个简单的程序谈起--之一
由一个简单的程序谈起--之一yiditushe
 
lecture2-PerlProgramming
lecture2-PerlProgramminglecture2-PerlProgramming
lecture2-PerlProgrammingtutorialsruby
 
B.Sc.Certification of Degree Completed_high resolution
B.Sc.Certification of Degree Completed_high resolutionB.Sc.Certification of Degree Completed_high resolution
B.Sc.Certification of Degree Completed_high resolutionKanutsanun Bouking
 
Comunicato Stampa Ae 280607
Comunicato Stampa  Ae 280607Comunicato Stampa  Ae 280607
Comunicato Stampa Ae 280607gianlkr
 
Devoxx%202008%20Tutorial
Devoxx%202008%20TutorialDevoxx%202008%20Tutorial
Devoxx%202008%20Tutorialtutorialsruby
 
Rappers and Brands Source Article
Rappers and Brands Source ArticleRappers and Brands Source Article
Rappers and Brands Source ArticleLulaine Compere
 
Athens Datacentres And 10 G
Athens Datacentres And 10 GAthens Datacentres And 10 G
Athens Datacentres And 10 GGianluca Musetti
 
M Y S P I R I T U A L Q U E S T O N D R
M Y  S P I R I T U A L  Q U E S T O N   D RM Y  S P I R I T U A L  Q U E S T O N   D R
M Y S P I R I T U A L Q U E S T O N D Rdrsolapurkar
 

Viewers also liked (13)

An%20Intermediate%20Google%20SketchUp%20Tutorial%20-%20Part%203
An%20Intermediate%20Google%20SketchUp%20Tutorial%20-%20Part%203An%20Intermediate%20Google%20SketchUp%20Tutorial%20-%20Part%203
An%20Intermediate%20Google%20SketchUp%20Tutorial%20-%20Part%203
 
silhouette2
silhouette2silhouette2
silhouette2
 
psager
psagerpsager
psager
 
由一个简单的程序谈起--之一
由一个简单的程序谈起--之一由一个简单的程序谈起--之一
由一个简单的程序谈起--之一
 
lecture2-PerlProgramming
lecture2-PerlProgramminglecture2-PerlProgramming
lecture2-PerlProgramming
 
B.Sc.Certification of Degree Completed_high resolution
B.Sc.Certification of Degree Completed_high resolutionB.Sc.Certification of Degree Completed_high resolution
B.Sc.Certification of Degree Completed_high resolution
 
Comunicato Stampa Ae 280607
Comunicato Stampa  Ae 280607Comunicato Stampa  Ae 280607
Comunicato Stampa Ae 280607
 
Devoxx%202008%20Tutorial
Devoxx%202008%20TutorialDevoxx%202008%20Tutorial
Devoxx%202008%20Tutorial
 
Rappers and Brands Source Article
Rappers and Brands Source ArticleRappers and Brands Source Article
Rappers and Brands Source Article
 
Athens Datacentres And 10 G
Athens Datacentres And 10 GAthens Datacentres And 10 G
Athens Datacentres And 10 G
 
66_pfSenseTutorial
66_pfSenseTutorial66_pfSenseTutorial
66_pfSenseTutorial
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
 
M Y S P I R I T U A L Q U E S T O N D R
M Y  S P I R I T U A L  Q U E S T O N   D RM Y  S P I R I T U A L  Q U E S T O N   D R
M Y S P I R I T U A L Q U E S T O N D R
 

More from tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 

More from tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Recently uploaded

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

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