Click here to Skip to main content
15,886,075 members
Articles / Web Development / HTML

AJAX AutoComplete control with JavaScript and PHP

Rate me:
Please Sign up or sign in to vote.
3.75/5 (3 votes)
29 Oct 2012CPOL4 min read 44.1K   1.6K   9   4
AutoComplete control for web-develepoment written in pure JavaScript

Download autocomplete.zip 

Introduction 

If you are looking for an AutoComplete web-control which is easy to implement into your web application then you are at the right place! This tool is lightweight but still effective and very easy to customize it through css classes. You can wire it up to an html <code><input> tag and set it up in minutes. It can receive any kind of datasets through a php site with AJAX callback so no postbacks are done while search is in progress (it is also possible to call .aspx or other kind of dynamic pages). But let's see some pictures instead of talking: 


Background 

When you start googling for same kind of autocomplete controls the first you are going to find is the jQuery UI Autocomplete Widget. After spending days with understanding the jQuerys' solution and program logic I gave it up and decided to write my own AutoComplete control. I don't want to blame jQuery just found it difficult to read their code.

So this control was written in pure JavaScript so you won't need any external resources like jQuery.

Using the code  

Using and setting up the control is very simple. This article won't go in deep analyzis how this tool works and what is happening behind the scenes in the core JavaScript file. It will just show you how you can implement and customize it for your needs (if you are interested in how the script works just send me an email). There is a fully working example attached to this article if you want to test it. All you need is an Appache server running on your OS (my advice is to use XAMPP for Windows users). 

In index.php we will add an <code><<code>input> tag and hook it up with the initializer script included in search.js. The onkeyup event will call up the InitAutoComplete() function which will be described later. We pass through the event and the control_id parameters to the function. These are mandatory values without this paramaters the control won't be able to be initalized. But for now here is the complete index.php codeblock (it's simple, hell yeah!):  

HTML
<!doctype html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2" />
<title>Autocomplete example</title>
<link href="css/search.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="java/autocomplete.js"></script>
<script type="text/javascript" src="java/search.js"></script>
</head>

<body>
  <div>
  <form>
    <div id="searchDiv">
      <input id="search" onkeyup="InitAutoComplete(event, 'search');" autocomplete="off" size="28" />
    </div>
  </form>
  </div>
</body>

</html>  

The initializer function is declared in search.js file. It has been simplified as much as possible for programmers who were trained in program language similiar to C#. It is fully Object Oriented and structured so won't be difficult to read the code (if you compare this with jQuerys' concept you will find this quiet a friendly code). Any kind of initializing steps should be done here. These values can be specified by You. 

  • Source: this is the dynamic page where the HttpRequest will be sent and from where the HttpResponse will be received (can be PHP, ASPX, whatever...). The response should be formatted as a JSON response array. 
  • QueryString:  usully "q" or  "term" but this is also up to you. On your php page you are going need to request this parameter and its value from the url (PHP e.g.: $_GET['q']). 
  • Delay: with this property you can specify the delay between key strokes those who sent to the server in milliseconds. 
  • MinLength:  this property will define the characters from which the search will start from.
  • SearchCaption: you can specify the displayed caption text when a request is in progress.
  • CssClassBox: you can assign here a css class that will be applied to the search box. 
  • CssClassLabel: you can assign here a css class that will be applied to the search result list captions.
  • CssClassProgress: you can assign here a css class that will be applied to the search box when a request is in progress and search is "busy" mode.
  • CssClassSelected: you can assign here a css class that will be applied to the selected search result element.
And here is the function defined in the search.js file that will initialize the AutoComplete control and also arm it (still simple, isn't it?):

JavaScript
function InitAutoComplete(event, input) {
  var myAutoComplete = new AutoComplete(input);
  myAutoComplete.Source = "search.php";
  myAutoComplete.QueryString = "q";
  myAutoComplete.Delay = 300;
  myAutoComplete.MinLength = 1;  //start search after 1 character
  myAutoComplete.SearchCaption = "Search...";
  
  //look and feel (if you don't set these options, it will use the built in default css classes which are quiet nice)
  myAutoComplete.CssClassBox = "searchBox";  //these classes are defined in search.css file
  myAutoComplete.CssClassLabel = "searchLabel";
  myAutoComplete.CssClassProgress = "searchProgress";
  myAutoComplete.CssClassSelected = "searchSelected";
  
  //fire
  myAutoComplete.Execute(event);
};  

And that's all! You just need to customize your own php/aspx callback page that will respone to this ajax call. Obviously there can be a lot of possibilities how you write your server side code and what you want to achive and what kind of results are you expecting from the server. Just keep in mind that you need to answer to the request in JSON array (for PHP there is a function called json_encode() to do so). Here is a working example how you can response (answer) with search.php

PHP
<?php
//fill the array with test resultset
//you can implement your own query here. E.g: fetching data from some sql database, like mySQL.
$result = array();
array_push($result, json_encode(array("seriesname" => utf8_encode("Stargate Atlantis"),
                                      "image" => utf8_encode("<img width=\"195\" height=\"40\" src=\"http://thetvdb.com/banners/_cache/graphical/70851-g12.jpg\">"))));
array_push($result, json_encode(array("seriesname" => utf8_encode("Stargate SG-1"),
                                      "image" => utf8_encode("<img width=\"195\" height=\"40\" src=\"http://thetvdb.com/banners/_cache/graphical/72449-g6.jpg\">"))));
array_push($result, json_encode(array("seriesname" => utf8_encode("Stargate Univers"),
                                      "image" => utf8_encode("<img width=\"195\" height=\"40\" src=\"http://thetvdb.com/banners/_cache/graphical/83237-g4.jpg\">"))));
array_push($result, json_encode(array("seriesname" => utf8_encode("Stargate Infinity"),
                                      "image" => utf8_encode("<img width=\"195\" height=\"40\" src=\"http://thetvdb.com/banners/_cache/graphical/11416-g.jpg\">"))));

echo implode(",", $result);
?> 

Installation   

For implementing the control you are going to need the following files: 

  • ./css/search.css (this will define the look and feel of your search result box, result captions and progress indicator) 
  • ./java/autocomplete.js (this is the core, if you are a JavaScript programmer you can override and extend the code for your needs) 
  • ./java/search.js (this will initialize the control and it should kept separately from the rest of the codeblocks) 
And you will need to wire up the InitAutoComplete() method with the onkeyup event:

HTML
<input id="search" onkeyup="InitAutoComplete(event, 'search');" />

Points of Interest 

Developing this control was a useful practice for me to learn JavaScript language. It was very challenging to think differently because programming some application in C# is way different then programming in JavaScript. Things are really working otherwise then you would expect it (personal note: start learning with JavaScript and then start learning C#). 

And remember: KEEP IT SIMPLE! 

History 

VERSION 1.0

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Website Administrator
Hungary Hungary
Working with Microsoft Dynamics NAV since 2007.

Comments and Discussions

 
Questionhow to exit the autocomplete dropdown after selecting value Pin
raja_rech12322-Apr-13 4:08
raja_rech12322-Apr-13 4:08 
GeneralMy vote of 1 Pin
bhawin parkeria14-Apr-13 22:19
bhawin parkeria14-Apr-13 22:19 
SuggestionPHP AJAX SEARCH Pin
Wilbert Santos2-Feb-13 15:43
Wilbert Santos2-Feb-13 15:43 
QuestionTrying the Autocomplete box Pin
Member 979213529-Jan-13 9:48
Member 979213529-Jan-13 9:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.