Before Start
The aim is to design an auto complete script for text box in ajax using Jquery, PHP, Mysql. I have searched for the script, and i have found a simple autocomplete plugin here http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ and you can find the documentation here http://docs.jquery.com/Plugins/Autocomplete.
You can download the source and see the Demos. But there is no demo fetching data from mysql. Then i have done some small trick in the php file to get data from mysql. This will be very useful in search suggestions, City, State fill up in some registrations.
HTML – Understanding the Layout
Here i have taken course names for example. I have a text box named and ided course. Thats all you need to know in the html layout.
<input type="text" name="course" id="course" />
JS – Include autocomplete plugin and activate
Download the autocomplete source from http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ and get the jquery core, autocomplete javascript file and css file. Include them inside the head tag. After that write some code to activate the text box with autocomplete.
<script type="text/javascript" src="jquery.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#course").autocomplete("get_course_list.php", {
width: 260,
matchContains: true,
selectFirst: false
});
});
</script>
To know the autocomplete plugin options go to here http://docs.jquery.com/Plugins/Autocomplete/autocomplete and see the Options tab.
PHP – Get data from DB
Get the query word and search within the database and return the list. (get_course_list.php file mentioned in the above javascript)
<?php
require_once "config.php";
$q = strtolower($_GET["q"]);
if (!$q) return;
$sql = "select DISTINCT course_name as course_name from course where course_name LIKE '%$q%'";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
$cname = $rs['course_name'];
echo "$cname\n";
}
?>

Using your script and working perfectly so far, with a few tweaks.
Have a question how can i get another varibale passed from (get_course_list.php to the index page, say course_id
thanks
Thank you for getting this going with PHP!
How could I pass both the id field along with the rest so I may put it in a hidden filed ?
Johnny,
Tariq,
Sorry for the late reply.
how to get name as well as id (in hidden field) – Please refer the next post.
Pingback: Ajax Autocomplete – Part 2 – with name and value « Beschi's Works
very very very very thanks
excellent thanks
this plugin is awesome but their is one problem when tried to delete item from list when i am used multiple:true then it not work
will you please tell their any configuration in autocomplete.js or any extra parameter i have to pass?
pls help me
honestly the best autocomplete plugin i ever found. great job! it’s really easy to use!!
thank you. send me an email if you want
Thanks Kratos,
//send me an email if you want//
want?
bonsoir Beski,
je trouve votre astuce très intéressant et j’ai besoin de récupérer l’ID de la fiche au lieu du Course_name pour que je puisse faire un update sur la fiche sectionnée en se basant sur celui-ci (ID) .
merci de me filer un coup de main qui vas énormément m’aider.
HI, I WANT SELECT DATA FROM MYSQL AND VIEW ON CYRILIC….HOW????
Also I’ve Problem bro…..
Use utf-8 in file get_course_list.php
How do you increase the results to be more than 10?
use “cacheLength” option for the plugin (page: http://docs.jquery.com/Plugins/Autocomplete/autocomplete)
$(“#course”).autocomplete(“get_course_list.php”, {
cacheLength: 15 /*default 10*/
});
Hello,
First thanks for all your helps !
With all your explanation my autocompletion works fine, except “cacheLength: 15″ !
I always have 10 records shown.
Do you have an idea why ?
For info, I practically didn’t customize the code you gave us above.
Thank you
Laurent
Sorry,
that was wrong.
To limit the results showing, use option: max: 15,
Thank you.
Hi is there a way to omit commas from the characters a user has to type for a input? My database New York, NY i want the user to be able to type New York NY 10011 and still be able to have New York, NY display
hi. im testing this jquery.autocomplete and is it possible to add a combobox and sent the combobox value to the config.php page and $_get it there.
here it is… autocomplete script loads on document ready itself, so use jquery keypress & use it check when an input field is keypressed
$(“#addbook_vehno”).keypress(function() {
$(“#addbook_vehno”).autocomplete(“config.php&vid=”+$(‘#new_carid :selected’).val(), {
width: 260,
matchContains: true,
selectFirst: false
});
});
nice tutorial . i have implemented something similar using jquery here
http://youhack.me/2010/04/28/creating-a-fancy-search-feature-with-php-mysql-and-jquery/
It’s basically the same .
how passing the data through if $cname has the enter value (\r\n)
$().ready(function() {
rewrite to
$(document).ready(function() {
where i can pass q to get_course_list.php?
is it ok if i pass variable like this:
$(“#Lcourse”).autocomplete(“getFriendMale.php?pesan=”+document.getElementById(‘course’).value, {
……
Excellent example for a newcomer to jQuery, best/easiest I have found.
I’m trying to adapt it to do multiple comboboxes with each one based on value selected in the prior one.
I.e. select vehicles specs: year, then makes for the selected year and then models for the selected year and make.
I have the inputs working with faked data or rather with fixed SQL. Where I’m stuck is to use the selected year to populate the make box. I.e. pass the selection the user made to the php script that does the SQL.
Any help greatly appreciated.
The first script that i tried and that really fits. Thanks
i tried your script and its not working, error says $() is not defined. why is that?
I got it working with: mysql_query (“SET NAMES ‘utf8′”);
It works perfectly but I have a latin db and the punctuations like áéíóúñ are simolized with a � any ideas ?? I’ve changed utf8 to iso and tried out utf8_decode
header(“Content-Type: text/html; charset=ISO-8859-1″,true);
why?
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\zyn\ajax-autocomplete\get_course_list.php on line 8
Getting same error .. solution plz
How to add “images/loading.gif” when loading?
Sorry,
I missed a file – indicator.gif. Now uploaded in the demo. You can see the loading gif file name in the css file.
Download any gif loading file, rename it indicator.gif and put it in the folder. Or edit the css file according to the gif file name.
Thanks.
it’s just easy yar
I solved the issue i had with the spanish punctuation marks inserting mysql_query (“SET NAMES ‘utf8′”);
Very nice! I enjoyed the read
2 things: I added the following so that an error message shows up when no results are found:
$num_rows = mysql_num_rows($rsd);
if ($num_rows == 0){
echo “No results.”;
}
What I’m wondering, is it possible that you can make it unclickable so that the input doesn’t then fill with a “No results.” value?
Also– not to do these at the same time, but would it be possible to open a new window via clicking on “No results.” when it drops down?
Okay, so I found this that should reload another URL when a link is chosen:
var data = [ {text:'LA', url:'/page1'}, {text:'Link B', url: '/page2'} ];
$(“…”).autocomplete(data, {
formatItem: function(item) {
return item.text;
}
}).result(function(event, item) {
location.href = item.url;
});
But when I add it to the head javascript of test.php nothing happens. Right now I have LA as the “link” since that’s the entry in my database that shows up. Any ideas?
By the way, found that piece of code on the jquery site @ http://docs.jquery.com/Plugins/Autocomplete#Demos
Thanks a lot i can make it
What do the two buttons do?, Sorry for the ignorance.
It is very nice code! I like it! Thank you for your demo.
thank you… i think this is what i’m looking for. i’ll try this now…
it’s working… i love it… hehehe… thank you so much…
Fine.
Pingback: 2010 review – Pagination and anchor scroll are most wanted | Beschi's Works
Really……….Its Wonderful.It works for me great.It is very simple to understand.
Thanks
Hi,
Very nice… but I have a little question:
How can I display the suggestions in a div id?
I hope you understand…
Thanks!
Thanks George.
Please mail the details (with sample code if possible…)
Hi I have adapted your script and it´s work almostfine now. Just something I could not do is: I want when people press enter and the script will open the link at once ( don´t need to press submit again there http://feemfans.com/test2.php (use keyword “a ” for testing
Thanks for further help.
Hi Alex,
refer the autocomplete part 2 – you can handle the call back when someone selects an option.
$(“#course”).result(function….
- here you can make the form submit.
Thanks for replying, you are very kind. it very useful but I have no idea to make it work perfect like this http://www.auto-suggest.com/ext-demo-standard/std_green.html
So sad
Thank you Beschi! For people who are searching a table with entries that contain apostrophes: make sure you addslashes to the query going in and strip them coming out. If you don’t, your query will still return results but when you select an item with apostrophes from the returned dropdown list, it’s not going to be found in the database and you will be left with a blank input box.
$q = (strtolower(addslashes(trim($q))));
$course_name = (stripslashes($rs['course_name']));
Thanks Brandon.
I’ve got the similar problem!
whatever i type sth, a blank line is revealed as the first item in the dropdown list.
how can i resolve it?
thanks!!
Did you solve this problem? That sounds different from what I was describing above. If you only get a blank line when typing in “sth” you should probably check your database to see what result row is being returned. See what’s different about the data in that row to see why you are getting a blank line. Check if the field has an apostrophe, etc.
Hi Beschi,
Very useful tutorial, Really nice.
I am appending this feature in my project, I have two query in this
1)for some cases i am not able to select the value from the list. If i select it will disappear. But it will list perfectly for me in the drop down list, If i try to select the value will disappear.
2) query is if i select the default value i.e recognize, “recognize ” will appear in the selection box.
Thanks,
Vivek
If I have a database with both eg. CourseID and CourseName, and I want it to be possible to search for them both in the search input, and it shows like:
“S134421 TheCourseName” as matched courses, but when I choose a course I would like it to only be returned as “S134421″, skipping the CourseName…
How to get this? Guess it has something to do with formatMatch, formatItem, formatResult? Don’t know how to implement it though…
Thanks!
Hi Robin,
Refer the next post (with value).
I guess your data returns [id], [id course] and displaying [id course], on result function set the [id] as value…
Beschi A.
Hi. This is awesome, thnak you Beschi. Looked for hours and hours for something that worked.
I have one question which i can see others are interested in as well. I have to searches where the last uses the ID from the first. How is this posible? I know i can set the value of a hidden input field, but i dont know where to put my javascript ‘onclick’ etc. Again. Thanks so much!!
Its in part two , havent seen that.
the Demo is really slow and does not load up in time!!
“$q = strtolower($_GET["q"]);” hi can you tell me how is ‘q’ used here ??
I don’t really get this part and I’m new to Ajax.
Good Work…But its not working when calling jquery funtion more than 8 times… I am new to jquery. What is the solution for this?
Hi
Thanks for the amazing script.
I was trying to clone the autocomplete text box.
do u have any scripts for that?
thanks
ccc
thnx bro… it’s the most easy and amazing script that i have ever seen in net… but one problem is ….
can u tell me… how can i get the the results to be more than 10?… that means how can i get the hole list when i put the search string. please help me out bro…
in previous post u said that.. to use “option: max: 15.. “.. the default value of max is here 100 .. did u mean that to change it 100 to 15?? plz tell me in details…
Yes,
http://beski.wordpress.com/2009/11/20/jquery-php-mysql-ajax-autocomplete/#comment-566
have you tried?
Thanks,
Beschi A.
yes i have tried it, bt its not working….
..the result is same as before.. it showing only 10 result.. please help me bro…
This should work.
Download the source of mine, create the table I have given. Then try this code.
$().ready(function() {
$(“#course”).autocomplete(“get_course_list.php”, {
width: 260,
matchContains: true,
selectFirst: false,
max: 15
});
});
This is working for me.
-Beschi A.
thnx bro thnx a lot… its now wrkng fine..
hi
very good code
i was searching 1 day for this code
very great and wonderful code
thnx to u all
Man I’m really glad that people like you post stuff like this on the web.
There are so many examples of similar functionality that it’s mind numbing. Of those countless examples, most authors assume that you understand the topic as well as they do & the instructions are obtuse. Of the remaining *very few* examples that are actually worth the time it takes to read them, most are still not well explained.
You just have whatever it takes to explain a complex subject in the simplest way. And your example code was working in under 5 minutes after uploading it to my server. With another 20-30 minutes it will probably be integrated into my core design. Thanks for being brilliant, & sharing it with the rest of us.
Thank you all.
It works very well for me, except when i clear the box since i decide not to enter a value after all, the hidden ID field still still holds the ID of the value I had selected initially.
Would you have a fix for this?
This is one way…
You can check this in form submit…
$(‘#your-form’).submit(function(){
if($(‘#input-elem’).val() == ”) {
$(‘#hidden-elem’).val(”);
}
});
not a bad idea, but is there no way to integrate this in your basic script? i would prefer to do this before the submit goes off (iff possible)
like only have the autocomplete.php being called when the field contains at least one character, and have the hidden id field emptied when when there is no character in it?
I’m having an issue using the plugin multiple times on the same page. Which part of the script do I need to modify? I already changed the get_course_list.php to another name, changed the $sql variable as well as the $cname variable, and attached the new scripts.
thank you so so match, this work
I have 2 days searching about a good examples like this
thanks
I want to set the drop down selected data text box value how can i?
Do you mean the variable value, or the options?
If it’s the variable, click his link at the top of the page for “Part 2″, he tells how to put a value (like an ID value) into it.
For options, follow his link above to the “options” — I made the visible drop down larger, and increased the results, by adding this:
max: 20,
selectFirst: true,
scrollHeight: 260
(In the code, underneath “matchContains: true,”)
Hi, very nice code but I had problems when having results in Greek, although I used :
mysql_query(“SET NAMES utf8″)
So, problem was solved by replacing :
$q = strtolower($_GET["q"]);
with :
$q = mb_strtolower($_GET["q"],’UTF-8′);
Now all is OK
File mou se eyxaristo para ma para poli gia tin lisi sou giati eixa terastio provlima!!kai mono esy to vrikes se olo to internet…ti na po…
Kai pali se eyxaristo poli!!!
Thank you very much my friend!!Just a great solution for Greek!!!!
Thank you! This really helped me.
Hi,
I’m having troubles implementing your code (very nice by the way)
It gets stuck loading (the graphic continues to spin with no results)
I’m positive the php sql file works. Where do you set what the value is? ie. the ‘q’ variable.
Could this be a css problem?
Any ideas?
I had that problem on one page. I had forgotten the top lines on the PHP page:
session_start();
ob_start();
It helped me a lot and save my time.Thanks a lot.
Hi,
thank you for you code.
I have a problem dealing with chinese,it seems that ajax does’t work. $_GET["q"] is empty.
i don’t know what’s the problem ,looking for help.
thanks a lot.
Hi,
Thank you so much for this script,
but I have a question :
When I writing in the label, I have my selection of my table and a number ( the one).
How delect this ?
Thank you
You are a very good man Sir Beschi! You are so generous in sharing your hard work.
Is this possible for multiple searchbox inside the form? Please help me if you have time. I know you are busy with your programming.
Thank you and be blessed!
I havn’t tried.
But it is possible.
Try and tell me if you have any problem.
Thanks.
I tried alot on it but unable to get the solution for multiple search box……help me if possible…thanx in advanc
I can’t seem to load this script. I get this error in Chrome Developer Tools:
Uncaught TypeError: Object # has no method ‘autocomplete’
Do you have any idea what could be wrong?
It’s working now. I was using both jQuery and Mootools and both use $ as an alias to a core function. So I just used jQuery instead of $.
Hi, I really love your script. However, I have one problem now which i am stuck for days!!
My form consists of other inputs and the dropdown suggestion does not ‘overlay’ the inputs.
Thus, I can see a textbox covering some of the suggestions.
Can you guide me how to set the CSS so that the suggestion box can ‘overlay’ all other elements on the page?
Thank you!
nice post…
Download link doesn’t work
THANK YOU MY FRIEND!
I have past 2 days trying to find the solution and nothing until find his post.
Realy: you R a GOD.
I cannot undertand why autocomplete JQUERY docs are so INCOMPLETE on SQL integration.
Thank you
Hi,
Resource was veru helpful, I need to add multiple courses via textarea element with the help of AutoComplete. May i know how can i accomplish this..Your Ideas are most Welcome
Thanks in Advance
Thank You Very Much…
I struggled with getting this done with other examples, but yours was clear and easy to follow.
finally i found the script to posted Beski. Thx alot. Now I am trying to find more script to enable the field for multiple values.
Pingback: AJAX Autocomplete PHP Tutorial | KC-TUTOR
how can i find the “config.php” file?
or what does the config.php contain? login to the database?
thanx boss
Thanks, it work and helped me so much…..
I also created and shared like this tutorial here for everyone.
EXCELLENT
Spent hours looking online for an Autocomplete that worked. This is great. Works beautifully!
Thanks!!!
#########################################################################
Hello! excellent work man. But i have a question, how can i disable submit button until valid selection is made form drop-down box, in other words speaking no “submit” button until value matches one in database ?? i that possible with out calling query again to database?
thank you
#########################################################################
Try property – mustMatch: true
Thank you for you response, yes i tried this option but submit button will submit whatever i type in the box because drop-down window wont disappear or wont take an action when i hover mouse outside of text-box or drop-down (autosuggestion) menu, before mustMatch can take over i have to click outside the menu or textbox. Do you see the problem here?
Thanks.
Thanks, it’s very good and simple.
ok, figured out the this part by modifying the code. How can pull more data from mysql to add pictures to it?
Hello,
I need help how can i pass any costume value along with textbox value
eg. [ $("#course").autocomplete("get_course_list.php", ]
What i want to also pass category id with “course” ??
Plz advise me
Thanks
Good job!
thank’s
working great.
how can we set up that to show data in input which is selected
Its 2012, and I <3 you OP
Is it possible to add in this result-list “serch-key” from clients (just overhead). I mean to show list with results words from Database and with “serch-key” from clients overhead those list , and show only 1 more time. For example…
I have Database with post offices from many states and regions.
1 region – Europa, number 98
2 region – USA, number 09
And I have many states from Europa and USA, like Berlin from Europa with number (98)521 and from USA with (09)112. So wenn a klient is trying to serch “98″, I want to show him not only result like “Berlin”, but also this region like “Europa” with extra CSS style overhead state Berlin, but to show only one more time. You have loop in your script, and it shows a lot times).
Or how to make just showing what client typing (overhead) and a result from Datebase at the bottom also.
Very nice and helpful article. Thankyou
Work awesome!
I have one problem though. In your demo, as we type, the matching alphabets/phrase gets highlighted/bold but on my textbox it doesn’t. How do I solve this?
Thank You.
Hello! is there anyway to add line “not found” and make it in form of a link ??
Thanks
Thanks Allot very helpful
There is no query validation on this .. I would personally validate the query, otherwise you’re just asking for a SQL injection.
I was worried about this too, so I used a prepared statement to validate $q, after I got the SQL to pull all of the correct information.
Reblogged this on Faysal Ahmed.
Hey, this is very nice example and it works perfect in a few seconds. thx
Just wanted to let you guys know if you do you SQL query with the (Lower) it can pull the DB and match all cases.
SELECT DISTINCT Name FROM Table where LOWER(Name) LIKE ‘%$q%’ ORDER BY Name ASC
very nice code. BUT is there a way, to also return the id of that row? not just name. I can obviously return the name of the search, but i would like to get the ID (int) of that row.
Please check the next post – Autocomplete Part 2.
Is this possible for multiple searchbox inside the form? Please help me if you have time.I tried alot on it but unable to get the solution for multiple search box……
wow tha’s really good and very veyr helpfully code thank you dear
Hi, is it possible to get other data mysql apart from the course_name. Thanks!
Heyyy….. this is awesome …. works fine for me …. thanks a LOT……
I did not got mysql result…how can i solve this problem….?
Is it possible to add a close button to the autocomplete drop down list?
Thank you very much is it really useful for me
could any one help me “how to change list position” please
hi, thanks for your great tutorial!! can you provide tutorial on how to include image icon and text elements in the autocomplete list?
other than that, let’s say i have a table with id, bookname, author, publisher fields. I have to search a book when enter bookname or either author or publisher. for author and publisher, it will return a bookname belong to that author or publisher. But how to do that? hope you can understand it. I was quite weak in SQL.
Pingback: Script installation service
Hello
First of all thank you for the great code!!!!
I just have a problem, i want to search in greek but i do not get any results..just in english…i have utf8 everywhere encoding,header, everywhere also in set names…can u help me?
Thank you very much!!!!
Konuyu bu kadar kolay ve güzel anlattığınız için çok teşekkür ederim. Allah Sizden Razı olsun. Bilginizi arttırsın.
EN: Topic Thank you so much for telling it so easy and beautiful. God bless you. FYI God.
Thank you very much!
To start with, hypertension, also referred to as high blood pressure can be a awful ailment that may be frequently involved to some very poor way of life. blood pressure medicine Depending on the quantity of strain you encounter everyday and actions in a different time of working day, your blood pressure level readings will vary. * Aronia berries can reduce blood clots from developing and therefore decrease the incidence of atherosclerosis.
hey my code is not working cn u help plz …. i thinks its a little bug which i am unable to find !!
here is the code its 1st file:
$().ready(function() {
$(“#uname”).autocomplete(“get_course_list.php”, {
width: 260,
matchContains: true,
selectFirst: false
});
});
username:
its 2nd file:
my database filed name is username , the problem which m facing is that, its not showing matched keywords, instead of that its showing the whole username field names , e.g if i press f then it appears all names of the field sorting is not happening!!
Very nice post, Like it.
Waseem Akhtar Tanoli.
Brilliant post but getting the following error;
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\NetBeansProjects\Mogadishu\getDeviceName.php on line 8
Any idea how I can solve this?
Best regards
Solved!
Reblogged this on Alfan Nasrulloh and commented:
Mantab sekali, sudah dicoba dan berhasil
Hello,
When I click the submit button I be directed to my page with the search results. EX: ” ”
Thanks
Furthermore, there’s evidence showing that antinutrients act as endocrine disrupting substances, promoting metabolic syndrome20. The Cavemen Diet May Be The Answer To Your Acne WoesCystic Acne Can Be Related To DietThe paleo is also known” The Caveman Diet, beating yourself up over it won’t help.
As with any diet, you don’t experience those blood sugar-fueled cravings. I made this dish for breakfast and a salad for lunch or dinner. Whether you choose to follow a paleo seem to do so because it actually works.
How do can i replace mydomain?cource=value+need+find ==> mydomain/search/value+need+find when press Enter ?. Thanks very much!
How To give action On Autocomplte Form On Single Press On enter how to do this
Pingback: Open Layers + Nominatim + Autofill |
The below blueprint will give you the skills to help build traffic for your online business you
should consider finding best Profit service provider.
They mark those word as a SPAM! While these article directories and many of that
are fake and some them are good and we can trust. They are applying innovative and creative
ideas to rebuild their online image.
The cramps are really painful the initial 1-a couple
of days, that I attended close to passing out.
You might still rely on us, for superb-quality party bags, party shoes and
accessories at great prices. “No one could have ever thought it of him,” Quinn said.
Nice scripts It”s Working Thanks But I Want add stylish scroll in it How to!!
As long as you start looking at yourself instead of those around you.
Get My Husband Back Many times we hear someone say to us, even when the dancing does.
Schools will now be left to draw up their own curriculum
for the non-compulsory subject, which is not fun to be around that person
any more. Non-monogamous get my husband back are surprisingly common and the numbers are increasing, according to Theravive.