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
May 26th, 2007 at 6:38 am
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);
May 26th, 2007 at 8:27 am
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
May 26th, 2007 at 9:10 am
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.
May 26th, 2007 at 9:38 am
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.
May 26th, 2007 at 10:10 am
Finally I rebuild all and even just opening the unzipped files directly from disc in firefox throws JS warnings. Can anyone confirm this?
May 26th, 2007 at 11:13 am
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.
May 27th, 2007 at 11:48 am
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.
May 27th, 2007 at 1:48 pm
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
May 28th, 2007 at 5:15 am
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.
May 28th, 2007 at 2:28 pm
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.
October 31st, 2007 at 2:07 pm
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
November 5th, 2007 at 6:00 pm
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.
December 30th, 2007 at 10:32 am
Sorry where can i find dimensions.js and autocomplete.js file ?
December 30th, 2007 at 4:17 pm
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
December 31st, 2007 at 2:01 am
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 !!
January 18th, 2008 at 7:58 am
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
February 13th, 2008 at 6:05 pm
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
April 26th, 2008 at 9:09 pm
Looks interesting, i might start using this on new websites i develop.
April 30th, 2008 at 10:45 am
Greet work, thx!
May 5th, 2008 at 8:54 am
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 .
May 21st, 2008 at 1:35 am
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.
June 8th, 2008 at 1:27 am
Thanks!
Works great!!
June 26th, 2008 at 6:07 am
Im having the same problem as computerzworld, i cant get it to work with multiple search fields
Can anyone help?
June 26th, 2008 at 6:20 pm
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.
July 28th, 2008 at 6:26 pm
Thanks… `;)
July 29th, 2008 at 5:18 pm
JQuery is awesome…
August 15th, 2008 at 7:55 am
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.
September 16th, 2008 at 8:25 pm
thank you.
September 22nd, 2008 at 5:18 pm
@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…
September 29th, 2008 at 9:36 am
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
October 3rd, 2008 at 10:23 am
How do I populate de Array dynamically from MySql Query ? Need Help Please.
October 7th, 2008 at 11:17 am
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.
October 20th, 2008 at 1:24 pm
thank you
November 24th, 2008 at 8:56 pm
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.
December 1st, 2008 at 7:31 am
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
December 12th, 2008 at 2:03 pm
Is there a way to limit the results?
December 17th, 2008 at 1:11 am
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?
December 20th, 2008 at 3:22 pm
help pls How do I populate de Array dynamically ( from MySql Query.
December 22nd, 2008 at 6:32 am
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.
February 6th, 2009 at 1:48 am
great work!!
February 28th, 2009 at 9:09 pm
help pls How do I populate de Array dynamically ( from MySql Query.
March 31st, 2009 at 1:03 am
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.
April 10th, 2009 at 4:52 am
Awesome! One of the better auto-suggest scripts I have seen over the web. Need to try this one out!
May 1st, 2009 at 11:23 pm
Script does not display results if fonts are resized (ctrl + in firefox). Needs to recalc the result div before updateing the div results.
June 16th, 2009 at 3:36 am
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
How to show the not find message when no matching.
Cheers.
Thanks.
Thi Ha
June 16th, 2009 at 4:14 am
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
June 21st, 2009 at 12:52 am
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.
July 12th, 2009 at 8:07 am
Thank all.
July 17th, 2009 at 3:26 pm
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…
July 20th, 2009 at 7:56 am
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
July 29th, 2009 at 9:47 am
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.
October 21st, 2009 at 2:47 pm
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?
October 27th, 2009 at 11:47 am
How i retrieve data from data base not from array, please help
October 29th, 2009 at 4:59 pm
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?
November 12th, 2009 at 1:31 pm
Thanks
January 7th, 2010 at 5:37 pm
Thanks! This is a really simple implementation and was exactly what I was looking for. Thanks so much!
January 14th, 2010 at 4:03 pm
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
February 9th, 2010 at 1:38 pm
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) } });
February 15th, 2010 at 1:57 pm
Nice one, How do I go about changing the array of words to words from a mysql database
March 13th, 2010 at 6:55 pm
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.
May 10th, 2010 at 5:03 am
i have same problem as “resimler”
May 29th, 2010 at 9:38 am
Awesome! One of the better auto-suggest scripts I have seen over the web. Need to try this one out
June 10th, 2010 at 2:51 am
Cant wait for the multi field autocomplete, i’m having a hard time here
June 10th, 2010 at 2:54 am
when i use “autocomplete.php?”+document.form.item1.value + part=”
it doesnt update my list menu until i refresh my page
June 22nd, 2010 at 3:55 am
your Auto-Complete is not working but your live site is working good please upload the right code
September 1st, 2010 at 7:29 am
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.
September 21st, 2010 at 11:56 pm
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.
September 26th, 2010 at 8:25 am
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.
December 30th, 2010 at 8:35 am
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.
March 24th, 2011 at 8:54 pm
Great and simple script that get the job done!
One question, is there a simple way to make it case-insensetive?
May 3rd, 2011 at 10:07 am
Thanks for the scripts.
Help me lot.
July 4th, 2011 at 9:53 am
your Auto-Complete is not working but your live site is working good please upload the right code
July 14th, 2011 at 8:54 am
Thank you friend.This is a awesome tutorial.
July 23rd, 2011 at 11:28 am
What if I want to show values on the autocomplete list as a strings and return picked field as a ID ? resim yükle