Click here to Skip to main content
13,252,537 members (58,976 online)
Click here to Skip to main content
Add your own
alternative version


9 bookmarked
Posted 27 Oct 2012

AJAX AutoComplete control with JavaScript and PHP

, 29 Oct 2012
Rate this:
Please Sign up or sign in to vote.
AutoComplete control for web-develepoment written in pure JavaScript



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: 


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!):  

<!doctype html>

<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>

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


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?):

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";

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

//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=\"\">"))));
array_push($result, json_encode(array("seriesname" => utf8_encode("Stargate SG-1"),
                                      "image" => utf8_encode("<img width=\"195\" height=\"40\" src=\"\">"))));
array_push($result, json_encode(array("seriesname" => utf8_encode("Stargate Univers"),
                                      "image" => utf8_encode("<img width=\"195\" height=\"40\" src=\"\">"))));
array_push($result, json_encode(array("seriesname" => utf8_encode("Stargate Infinity"),
                                      "image" => utf8_encode("<img width=\"195\" height=\"40\" src=\"\">"))));

echo implode(",", $result);


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:

<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! 




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


About the Author

Mihaly Sogorka
Website Administrator
Hungary Hungary
Working with Microsoft Dynamics NAV since 2007.

You may also be interested in...


Comments and Discussions

Questionhow to exit the autocomplete dropdown after selecting value Pin
raja_rech12322-Apr-13 5:08
memberraja_rech12322-Apr-13 5:08 
GeneralMy vote of 1 Pin
bhawin parkeria14-Apr-13 23:19
memberbhawin parkeria14-Apr-13 23:19 
Wilbert Santos2-Feb-13 16:43
memberWilbert Santos2-Feb-13 16:43 
QuestionTrying the Autocomplete box Pin
Member 979213529-Jan-13 10:48
memberMember 979213529-Jan-13 10: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171114.1 | Last Updated 29 Oct 2012
Article Copyright 2012 by Mihaly Sogorka
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid