Auto-Complete Field with jQuery, JSON & PHP

In the last few days I’ve started using the jQuery JavaScript library. To experiment with this great piece of software I’ve decided to implement an AJAX auto-complete feature. jQuery makes remote scripting a piece of cake and that led me to spend more time coding additional functionalities for the auto-complete field. In this post I’ll explain how to use my auto-complete field and in a following post I’ll explain all the code. So let’s start!

Before continuing let’s see how the auto-complete field looks like. Start typing some color name in the input field bellow to see how it works:

Pretty hugh? Besides the auto-complete code we need the jQuery library along with its Dimensions plug-in (all files are linked at the end of this post). Let’s include the files into our page:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dimensions.js"></script>
<script type="text/javascript" src="autocomplete.js"></script>

Now we need to call the function that will bring life to our auto-complete field - setAutoComplete.

<script type="text/javascript">
$(function(){
    setAutoComplete("searchField", "results", "autocomplete.php?part=");
});
</script>

The call to setAutoComplete is inside a jQuery special code that is only executed when the DOM is ready, or in other words, when all the code is already loaded. The setAutoComplete function takes 3 parameters:

  • the id of the input field
  • the id of the div that will hold the returned data
  • the URL of the remote script that will process the request

Be aware that the URL should reflect your remote script and that it will be combined with the text typed in the input field.

Now we include our stylesheet to define the look of the elements. We need to define the styles of the div that will contain the results, they include two classes for the selected and unselected items. Take a look at the CSS file linked at the end of this post. There is also a style for the input field.

<link rel="stylesheet" href="autocomplete.css" type="text/css">

To finish the client side part now we need to define the code of the input field as follows:

<label for="searchField">Colors: </label>
<input type="text" id="searchField" name="searchField">

We are almost there! Now that the client side is finished it’s time for the server script. Here is an example of a script that try to match colors. I’m using PHP but you can use whatever language you prefer for the job, of course. You just need to return the results as an array encoded as JSON.

// define the colors array
$colors = array('black', 'blue', 'brown', 'green', 'grey',
                'gold', 'navy', 'orange', 'pink', 'silver',
                'violet', 'yellow', 'red');
 
// check the parameter
if(isset($_GET['part']) and $_GET['part'] != '')
{
	// initialize the results array
	$results = array();
 
	// search colors
	foreach($colors as $color)
	{
		// if it starts with 'part' add to results
		if( strpos($color, $_GET['part']) === 0 ){
			$results[] = $color;
		}
	}
 
	// return the array as json
	echo json_encode($results);
 
	// or return using Zend_Json class
	// require_once('Zend/Json/Encoder.php');
	// echo Zend_Json_Encoder::encode($results);
}

Done! As said before, we return the data as an array encoded as JSON. If you are running PHP >= 5.2.0 or the json extension you simply use json_encode for the job. Another option is to use Zend_Json_Encoder from the Zend Framework!

You should have a working auto-complete field by now! Note that we don’t need to explicit create the result div because it’ll be created automatically. You should also note that the current script can be improved a lot and is limited to just one auto-complete field per page!

Keep tuned, in the next post I’ll explain how the JavaScript works!
Thank you!

Update: Click here to read the post where I explain the JavaScript code!

Files needed:

Auto-Complete (All files)
jQuery JavaScript Library
jQuery Dimensions Plug-in
Zend Framework

74 Responses to “Auto-Complete Field with jQuery, JSON & PHP”

  1. Frank Says:

    For php4 users (if you’re still bound to) you can use http://mike.teczno.com/JSON/ to encode to JSON.

    // return the array as json with PHP 4 and Services_JSON
    require ‘JSON.php’;
    $json = new Services_JSON();
    echo $json->encode($results);

  2. Frank Says:

    What’s a little pitty is, that mozilla tends to remember what has been already entered in that field. This is great in general but with your own autocomplete it is not because this is displayed above the autocomplete list. This can be made with the autocomplete attribute setting to off. Maybe it makes sense to put this into the .js as well?

    This is the code that did the job for me (tested in firefox 2.x) in autocomplete.js inserted at line #40 in function setAutoComplete:

    // remove browsers autocomplete
    acSearchField.attr(”autocomplete”,”off”);

    more info: http://chrisholland.blogspot.com/2004/11/banks-protect-privacy-disable.html

  3. Frank Says:

    Another comment: Using the PHP4 JSON.php lib is a bit problematic when it comes to unicode. For some german umlauts the code has got bugs resulting in problems for the autocomplete to properly work. It is strongly suggested in such cases to migrate to php5 as with everything unicode related.

  4. Frank Says:

    Well I don’t know what changed exactly (this is a joke, what changed is PHP to version 5.2.2), but calling the html (not any php) file gives a long list of javascript warnings already in jquery. my favorite ones are:

    clearAutoComplete is not defined

    or

    Warnung: variable a hides argument

    or

    Warnung: variable i hides argument

    I dunno what is going wrong here I’ll restart my system now.

  5. Frank Says:

    Finally I rebuild all and even just opening the unzipped files directly from disc in firefox throws JS warnings. Can anyone confirm this?

  6. fromvega Says:

    Hey Frank, disabling the browser auto complete is a good tip. Thank you! I’ll address this issue in the next version. I’m planning to transform it in a jQuery plugin as soon I have a little more time.

    Maybe your problem is that you are returning invalid data! Since the script uses jQuery $.getJSON function you should only return JSON.

  7. Frank Says:

    Hi fromvega! Yup that was my mistake, there was no proper JSON returned. If you’re after turning this into a jQuery Plugin (good idea!) keep in mind that it should work on multiple inputs on the same page. I could not figure out how to do that with your autocompete.

  8. fromvega Says:

    I’m glad it worked for you. And yes, the plugin will work on multiple inputs. I coded the current script mainly to study jQuery and its Ajax functions. To have multiple inputs with the current script you need to duplicate the code and rename the global variables for each input, like I described here in the Auto-Complete Field with jQuery - Code Explained

  9. Frank Says:

    Okay, well, I see. Maybe it’s better to support an already existing project? I found

    http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/

    which is an jQuery Autocomplete Plugin and it works very nice even without duplicating the sourcecode (which is not an option in my opinion). It already has some more nice options you should defenetly take a look there anyway even if you wanna start a plugin on your own.

  10. fromvega Says:

    Learning is what lead me to write these codes. I’m pretty sure there are a lot of similar scripts around the Internet. The one you linked is an example of a very good one, but I’ll keep writing my own code as it’s a way to improve my skills and help others detailing how they work.

    Plug-ins tend to embed code to give freedom to the user, allowing multiple configurations for different usages. My code tend to fulfill my own needs and most of the times they won’t have a lot of configuration. Sometimes it can be better if your needs are similar to mine, reducing the code and making it simpler.

  11. Jozef Says:

    Hello Frank,
    -I’m obviously not a programmer- So I am kind of embarrassed to ask.
    What/how do I have to change to use autocompleter like a link (html link to a folder)?
    Red - click - go to link- domainname/red/
    Blue - click - go to link- domainname/blue/
    For data source I can use XML or put the data inside the page.
    (how is the data source format should be)
    I wouldn’t mine paying for your help.
    Thanks
    jfk

  12. fromvega Says:

    Hello Jozef,

    The code responsible for populating the list is:

    newData += '<div class="unselected">' + json[i] + '</div>';

    So you would need to add a link tag, like this for instance:

    newData += '<div class="unselected"> <a href="address">' + json[i] + '</a></div>';

    That’s way it will be clickable. For the red, blue thing your PHP script will probably need to send more information to the JavaScript code so then you can decide watch address to link.

    I hope you could understand.

    Bye.

  13. Thailand Real Estate Says:

    Sorry where can i find dimensions.js and autocomplete.js file ?

  14. fromvega Says:

    Hi Thailand Real Estate, the files are listed at the end of the post, just before the comments! To get all the needed files, use this link: http://fromvega.com/code/autocomplete/autocomplete.zip

  15. kpli Says:

    Thanks for the lovely post, i’ve read it with interest and had bookmarked this blog for future reference..keep em coming bro, and i wish you A Happy New Year !!

  16. kpli Says:

    Hi..just stopping by to say a Happy New Year…interesting post there, and i’ve bookmarked this blog too…keep up the good job ;)

  17. ramon Says:

    i just made a simple autcomplete jus like the one in the example i took it for inspiration and made some adjustments http://webs2.x1fmradio.com

  18. Panzer Says:

    Looks interesting, i might start using this on new websites i develop.

  19. wissem Says:

    Greet work, thx!

  20. rehman Says:

    Hi,I’ve a problem with your code:
    When I put your zipped folder’s autocmplete.html file run on any browser it is not working with an javascript error.
    If I put their in the
    “start”
    $(function(){
    setAutoComplete(”searchField”, “results”, “autocomplete.php?part=”);
    });
    “end”
    instead of
    setAutoComplete(”searchField”, “results”, “autocomplete.php?part=”);
    setAutoComplete(”searchField”, “results”, “http://fromvega.com/code/autocomplete/autocomplete.php?part=”);
    it works.
    In Short Your zipped code is not working But Online code work Smoothly.
    So plz make your code perfect .

  21. computerzworld Says:

    I have two fields that are used for autocomplete. I have used your script which runs perfect for one field but how can I use it for two fields? I have tried to modify it but I wasn’t able to modify it. Please help me. Thank you.

  22. felicia Says:

    Thanks! :) Works great!!

  23. WoL Says:

    Im having the same problem as computerzworld, i cant get it to work with multiple search fields :(

    Can anyone help?

  24. fromvega Says:

    Hi computerzworld, hi WoL. Like I said in another comment from the other post (http://fromvega.com/wordpress/2007/05/08/auto-complete-field-with-jquery-code-explained/), this example was not designed to be used efficiently with more than one field. Although, if you still wanna use it you will need to duplicate the code and rename the global variables and functions for each field.

  25. FMS GROUP Says:

    Thanks… `;)

  26. Myrtle Beach Real Estate Says:

    JQuery is awesome…

  27. Marcum Says:

    Hi. Great code :-) I would like to one step further and have the array built from an xml file that is maintained on the website. I can use php simpleXml to get the titles into an array but I am not sure what changes are required to your code so that they are displayed. If it is not possible I will have just manually type them in, but then it is remembering to do it. Any help would be appreciated.

  28. resim Says:

    thank you.

  29. WarpKat Says:

    @Marcum: read in your XML and parse it as an array, then toss the array to the function - not all XML is created equal… =:D

    @All: Hello - this is a great short-method fix for what I needed to do, however, I do have a small inconvenience with it:

    The list returned is actually longer than the window it’s on. Is there a way to turn the results into a scroll-barred list or maybe make it so that the list overlays on top of the window itself so the complete list can show?

    I hope I explained that right…

  30. fromvega Says:

    WarpKat, you can set the “hight” of the list container to something that you want then use “overflow-y: scroll” so you can have scrollbars ;)

  31. Charly Says:

    How do I populate de Array dynamically from MySql Query ? Need Help Please.

  32. Aaron Reynolds Says:

    Your code works well and I haven’t had to tinker yet.

    Due to my Ubuntu install limiting me to PHP v5.1.2 currently I’ve had to use a 3rd party JSON encoder.

    Ended up adapting rewriting it for the purpose.

    Available at: http://dev.enjoyonline.co.uk/auto/ar_json_encoder.php.txt

    I’ll be coming back to keep up with your other work, thanks - Aaron.

  33. ev arkadaşı Says:

    thank you :)

  34. fromvega Says:

    Hey Charly, you can’t populate directly from a MySQL query. You need to run the query, get the results and then put them into a PHP array. After that you can use a json encoder to send the resulting data back to jquery.

  35. dino Says:

    hi vega

    i have a question, how do i configure it to have a comma on every input

    example

    name1, name2, name3

    whats happening now is when i put a comma on name1 then i choose again another name for example name2, name1 will be replaced by name2

    another question is:

    why is that when i input a word with one instace in my array in doesnt show up on the list but when i input with another input with many instances of that word it will show on list

    thanks in advance and great job on the code

  36. J Says:

    Is there a way to limit the results?

  37. refins Says:

    i am a newbie,
    I have a same problem with Rehman, the autocomplete doesn’t work in localhost
    if the script is setAutoComplete(”searchField”, “results”, “autocomplete.php?part=”);
    but it does work well
    if i put the script like this :
    setAutoComplete(”searchField”, “results”, “http://fromvega.com/code/autocomplete/autocomplete.php?part=”);

    because i’m using php v.5.1.1 so i try to download zend framework from
    http://framework.zend.com/
    (since there is a require file : Zend/Json/encoder.php)
    but the problem still happens
    i suppose it is caused by the version of the zend framework.
    Could someone help me,please?

  38. oyun hileleri Says:

    help pls How do I populate de Array dynamically ( from MySql Query.

  39. gebelikte moralsizlik Says:

    Hey Charly, you can’t populate directly from a MySQL query. You need to run the query, get the results and then put them into a PHP array. After that you can use a json encoder to send the resulting data back to jquery.

  40. car alarm system Says:

    great work!! :)

  41. toki Says:

    help pls How do I populate de Array dynamically ( from MySql Query.

  42. Mira Says:

    Hi. Great code :-) I would like to one step further and have the array built from an xml file that is maintained on the website. I can use php simpleXml to get the titles into an array but I am not sure what changes are required to your code so that they are displayed. If it is not possible I will have just manually type them in, but then it is remembering to do it. Any help would be appreciated.

  43. Webdesign Meppel Says:

    Awesome! One of the better auto-suggest scripts I have seen over the web. Need to try this one out!

  44. plc Says:

    Script does not display results if fonts are resized (ctrl + in firefox). Needs to recalc the result div before updateing the div results.

  45. Thi Ha Says:

    awesome. works like charm.
    Although I don’t know the back-end work, this is the simplest example I have ever find.
    Only one question :D
    How to show the not find message when no matching.

    Cheers.
    Thanks.
    Thi Ha

  46. Thi Ha Says:

    I got it but just adding this

    if(empty($results)){
    $msg[0]= “No matching”;
    echo json_encode($msg);
    }else{
    echo json_encode($results);
    }

    Another question is where to change the font size, it looks smaller.
    thanks
    thi ha

  47. ZK@Web Marketing Blog Says:

    It is built on top of the DOM, and unfortunately, the DOM is not always fun to work with. Luckily, we have an excellent DOM slicer and dicer that we can use alongside Strophe, the jQuery library.

  48. Komik Videolar Says:

    Thank all.

  49. Leon Says:

    Hi there, just a simple question… This autocompleter works if there are 2 text box in the page, because i’ve been trying make it and it doesn’t. Actually it seems that only take the last autocomplete that I wrote in my code… P.E:

    $(function(){
    setAutoComplete(”searchField”, “results”, “autocomplete.php?part=”);
    setAutoComplete(”searchField2″, “results2″, “autocomplete2.php?part=”);
    });

    this doesn’t work and i don’t know why… if anybody could help me please…!!!

    P.D.- Sorry about my english, I know it’s not very good looking… jejejeje…

  50. maie Says:

    hello
    In my script i made an array of text fields dinamically from the database
    so i want to apply the auto complete on each one but when i make that it does not work please help ASAP you can send answers on my mail
    white_horse2040@yahoo.com
    Thanks

  51. gaurav dubey Says:

    I have used this example and it works like a charm.
    But there is one problem.If I type “r”(lowercase) then it works fine, but if I type “R” there is no suggestions.

  52. Sathish Says:

    Hi, Your code is very useful, i used database instead of array and now i need to filter with respect to another field in the form, can u guide me pls?

  53. kurshom Says:

    How i retrieve data from data base not from array, please help

  54. Kris Says:

    Looks good, but strange thing happened.

    It requires data in format:
    [”item1″,”item2″,…]
    and JSON is something like:
    {0:”item1″,1:”item2″,…}

    Is this a bug or it should be that way?

  55. güzel kızlar Says:

    Thanks

  56. mark Says:

    Thanks! This is a really simple implementation and was exactly what I was looking for. Thanks so much!

  57. Peter Abolins Says:

    Hi fromvega,

    Did you ever complete the multiple input-field auto-complete version (pun intended)? I am modifying a website that used your initial plug-in and if there was indeed an updated version of your plug-in, it would save some work.

    If not, that is okay - I’ll write my own. Duplicating code (as was suggested for multiple fields) is for script-kiddies - not for programmers :-)

  58. Laurent Chevassu Says:

    I have found that clicking on the result div scroll triggered the search input blur event in WebKit, thus hiding the results.

    I came up with this hack (working, if not perfect, I couldn’t get to just prevent the blur event). It replaces and complements the line “on blur listener” in the original.

    scrollFlag = false;

    acResultsDiv.mousedown(function(){ scrollFlag = true; });
    acResultsDiv.mouseleave(function(){
    if ( scrollFlag ) {
    scrollFlag = false;
    acSearchField.focus();
    }
    });

    // on blur listener
    acSearchField.blur(function(){ if ( scrollFlag == false ) { setTimeout(function () {clearAutoComplete()}, 200) } });

  59. Hadith Says:

    Nice one, How do I go about changing the array of words to words from a mysql database

  60. resimler Says:

    I have two fields that are used for autocomplete. I have used your script which runs perfect for one field but how can I use it for two fields? I have tried to modify it but I wasn’t able to modify it. Please help me. Thank you.

  61. ajaz ali Says:

    i have same problem as “resimler”

  62. Goedkoop website laten maken Says:

    Awesome! One of the better auto-suggest scripts I have seen over the web. Need to try this one out

  63. Shah Says:

    Cant wait for the multi field autocomplete, i’m having a hard time here :(

  64. Shah Says:

    when i use “autocomplete.php?”+document.form.item1.value + part=”

    it doesnt update my list menu until i refresh my page :(

  65. ashfaq ahmed Says:

    your Auto-Complete is not working but your live site is working good please upload the right code

  66. Abhidev Says:

    Hey nice code….i m using ur code but then its not fetchin any results for the letters ‘b’ and ‘n’ in IE whereas it does for other browsers. My servelet returns the json properly. Pls help.

  67. Mark Says:

    I updated the script to allow multiple fields by changing the global variables to be arrays and passing the fieldid to the functions. Works fine now with multiple fields.

  68. anne Says:

    hello every one. I am a neophyte to software development. I just wanna ask about using the auto complete function. What are the software development tools you are using which has auto complete function which you see performs better than the others? please do take time to answer me.
    thanks.

  69. gemGreg Says:

    What if I want to show values on the autocomplete list as a strings and return picked field as a ID ?

    For example I have table “messages” with fields: “id”, “text” and I want to show to user text values to pick from, but send “id” of that row.

  70. Joseph Says:

    Great and simple script that get the job done!

    One question, is there a simple way to make it case-insensetive?

  71. Mariya Says:

    Thanks for the scripts.
    Help me lot.

  72. writers job Says:

    your Auto-Complete is not working but your live site is working good please upload the right code

  73. hotel doctors nationwide Says:

    Thank you friend.This is a awesome tutorial.

  74. resim yükle Says:

    What if I want to show values on the autocomplete list as a strings and return picked field as a ID ? resim yükle

Leave a Reply