Please support us by disabling ad blocker for smarttutorials.net ...

jQuery Autocomplete Search using PHP, MySQL and Ajax

Posted by & filed under Ajax, HTML5, JAVASCRIPT, JQUERY, MYSQL, PHP.

In this tutorial we are going to implement jQuery autocomplete search using PHP, MySQL and Ajax. This jQuery autocomplete gives suggestions when users starts to type on searchbox like in google search box. I had implemented two types of jQuery autocomplete

jquery autocomplete integration

1. Simple jQuery autocomplete

2. Populate multiple textbox with single jQuery autocomplete request.

please refer my latest tutorial on jQuery automplete

jQuery Autocomplete Mutiple Fields Using jQuery, Ajax, PHP and MySQL

Invoice System Using jQuery AutoComplete

For every letter user types something on textbox, ajax request will sent to the Apache server. There Apache server will commuincate with MySQL database and fetch some data’s based on the text users typed in the textbox. Finally Apache server sends the response to the ajax request sent by client, the response data will showed as suggestions to the users.

 

 

jquery-autocomplete-using-php-mysql-ajax

jQuery Autocomplete using PHP, MySQL and Ajax

Step 1:

Create following sample database and tables to implement this jQuery autocomplete functionality using following sql queries.

CREATE DATABASE IF NOT EXISTS `autocomplete` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `autocomplete`;
CREATE TABLE IF NOT EXISTS `country` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `iso` char(2) NOT NULL,
  `name` varchar(80) NOT NULL,
  `nicename` varchar(80) NOT NULL,
  `iso3` char(3) DEFAULT NULL,
  `numcode` smallint(6) DEFAULT NULL,
  `phonecode` int(5) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=240 ;
CREATE TABLE IF NOT EXISTS `names` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fruit` varchar(100) NOT NULL,
  `human` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=166 ;

Please download sql dump and source of this tutorial using blow Download link .

 

 

Step 2:

Create config.php file to have database connections in a separate file.

<?php
/*
Site : http:www.smarttutorials.net
Author :muni
*/
define('DB_HOST', 'localhost');
define('DB_NAME', 'autocomplete');
define('DB_USER','root');
define('DB_PASSWORD','');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
?>

Step 3:

Now create index.php file and create following textbox.

<input id="country_name" class="form-control txt-auto"/>

Step 4:

If you want to implement this autocomplete functionality minimum you need following jquery and css files.
(jquery.min.js, jquery.ui.min.js and jquery.ui.min.css). add following files in your index.php file.

<link rel="stylesheet" href="css/jquery-ui-1.10.3.custom.min.css" />
<script src="js/jquery-1.10.2.min.js"></script>	
<script src="js/jquery-ui-1.10.3.custom.min.js"></script>

Step 5:

This following jquery scripts will get whatever    user types in the textbox, and makes ajax request to the server with data, user entered in the textbox. Finally get the response from the server and shows as suggestions.

$('#country_name').autocomplete({
		      	source: function( request, response ) {
		      		$.ajax({
		      			url : 'ajax.php',
		      			dataType: "json",
						data: {
						   name_startsWith: request.term,
						   type: 'country'
						},
						 success: function( data ) {
							 response( $.map( data, function( item ) {
								return {
									label: item,
									value: item
								}
							}));
						}
		      		});
		      	},
		      	autoFocus: true,
		      	minLength: 0      	
		      });

Step 6:

create ajax.php file that will handle all ajax request from the client.

<?php
require_once 'config.php';

if($_GET['type'] == 'country'){
	$result = mysql_query("SELECT name FROM country where name LIKE '".strtoupper($_GET['name_startsWith'])."%'");	
	$data = array();
	while ($row = mysql_fetch_array($result)) {
		array_push($data, $row['name']);	
	}	
	echo json_encode($data);
}

?>

Please download source code(added all example code showed in the demo page)  of this tutorial using above download link..

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni[at]smarttutorials.net

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

  • eric fan

    hello, can email me this codding , im need use this for my reference, i need use this method in my project.. thank…

  • Prince

    I would like to receive the script. Please send it to my email box. Waiting for your reply

  • sethu

    hi,
    can u email me this coding.
    To: consultshakti@gmail.com

    thnx in advance

  • nilesh

    thanks for sending the code
    can you tell me how to add sroll bar to dropdown values of textbox

  • Plz send to my mail id ….

  • hi,
    can u email me this coding.
    To: navnit87@gmail.com

    thnx in advance

  • brijesh

    dear mumi, can you send me “Populate Mutiple Textbox with single auto-select Request” project file.
    at
    beokurud@gmail.com

  • Lan

    Can i have fullsource this examples, my email is: sima_y@ymail.com

  • JulioS

    Dear Mumi, u can send to me email with this code at julios@humam.com.br
    Tks!

  • Anand

    Can you email me the code,

    Very helpfull code.

    Thanks in advance..

  • muni

    Sent

  • muni

    sent

  • muni

    sent 🙂

  • aljadek

    Can you email me the code ?
    Or the full in zip ?

    Thx

  • haris

    Can you please send me the source code for this? I have spent days trying to develop this but keep getting errors, I would really appreciate it

    nj.haris@gmail.com

    thank you

  • Balaji

    Can i have full source code of this examples to my email id……….. i’m looking for this search for past 2 days

  • Pulkit

    Hey can u mail me full source code for this.
    Thanks 🙂

  • NEEL

    its very helpful for me thanks for sharing.
    I am was searching this type of auto complete, can you send me source code on my email: gupta.neel1@gmail.com

    Thanks

  • Sir,
    please send the code to my mail. its very urgent that i need this code. Thnk u in advance

  • Ezio

    hey, can you mail me the source code, it is a great tutorial thnaks.

  • dasa

    Hi Muni… nice code there… can you email me the code
    thanks in advance 😉

  • muni

    sent 🙂

  • muni

    sent 🙂

  • muni

    sent 🙂

  • shendi

    Can you mail me the code sir, thanks before. 🙂 sector.code7@gmail.com

  • Rajesh kannan

    It is a very useful tutorial.I need this,can u send me as soon as possible…Thanks in advance

  • Sir,
    please send the code to my mail. its very urgent that i need this code. Thnk u in advance

  • hendi

    Hi..
    sorry before…
    can you email me the code
    thanks and databese….?? to hendi_ep@yahoo.com

  • Hendi

    Hi..
    Can You email Code And Database To My Email…??
    hendi_ep@yahoo.com

  • Aswin K M

    Please mail me the code @ aswinkmhere@gmail.com… Thanks in advance.

  • longdonkey19

    why doesn’t the download work? Can I get the source pls.

    regards

  • Igor

    hi, can you mail me the source code, it is a great tutorial thanks.

  • ashish

    please send the code to my mail.
    my email is : – pathakashish.1966@gmail.com.
    its very urgent .
    thanks in advance 😉

  • kumara

    hi
    can u email me this coding
    to : kumara2009@ymail.com

    thanks

  • Hi Muni
    Excelent code there.
    Can you send me please.
    Thank

  • kamal

    good

  • sachin

    hey.. i subscribed to your site but still wasnt able to get the download link. Please send me the code.

    sachinjoshia14@gmail.com

  • longdonkey19

    Got it working and works a treat. but I just found out it doesn’t work in IE. Is there a fix for this or have I missed something?

    regards
    Sam P

  • Joe

    Hi Muni,

    Great code tutorial. Please can you email me the zip files of code, thanks.

  • sirshendu ghosh

    please send the code to my mail.”Populate Mutiple Textbox with single auto-select Request” My email id is sirshendu.ghosh@hotmail.com

  • Raffles

    awesome code…
    can you send source code for me ???

  • fon

    please send the code to my mail.i am need this code. thnx in advance

  • fon

    please send the code to my mail. thanks in advance : fon.0151@gmail.com

  • Adeel

    Could you please send me the code on mirzaadeel2000@hotmail.com

  • mohit

    Hi Muni… nice code there… gud job..

  • mounika

    hey.. i subscribed to your site but still wasnt able to get the download link. Please send me the code.

  • ramki

    Hi could you mail me source code please 🙂

  • ramki

    Can you email me the code ?
    Or the full in zip ?

    Thx

  • irwan

    Hi Muni,
    Great code tutorial. Please can you email me the zip files of code, thanks

  • marco

    Hi, very nice code. Can you send me the code, please?
    Is it possible to search in the whole record and not only the first letter?
    So, if i search “ama”, the results is both , ex, alabama and amarcord

    Sorry for the bad english

    thankyou very much.
    Marco

  • Vijay Chauhan

    Can you send me these code ??

    its very nice !!

    6233vijaychauhan@gmail.com

  • paul

    Would appreciate the source code. My email is pauln1130@gmail.com. Thanks.

  • wojtek

    hi, I have subscribed to your sub list but still no code, Can you please post the code to me please? Thank you

  • I am still waiting for the sql 🙁

  • Kem

    Hi could you send me the whole code for this, ill try convert it to PDO for my current project.

    Thanks

  • please send

  • Arvind

    Hi Can I too have the full source…
    Mail Id: arvind.mib@gmail.com

  • Arvind

    Hi can you send me the source code. Mail ID: arvind.mib@gmail.com

  • muni

    yes you can use ‘%ama%’ in your where condition

  • Hindujhan

    Can you please email this coding to my email

  • subbu vemuri

    Hi can you send me the source code. Mail ID: subbu19858016@gmail.com

  • muni

    sent

  • rocky

    send me plz

  • Jacob

    Hello i got full source code from you, but there is a problem. Why it doesn’t work for me ? I created database etc. When i i type in input field af im getting in console reply

    [“AFGHANISTAN”]<!–
    document.writeln('’);
    //–>

    but it doesn’t show the tip.

    you can check it http://www.schrack-seconet.pl/autocomplete/

    Please help me to solve this problem.

  • Hi Jacob,

    It’s problem due to script after closing tag. please remove that it will work fine.

    this is that script

    <!–
    document.writeln('’);
    //–>

    Many Thanks,

    Muni 🙂

  • Jacob

    Hi Muni,
    thanks for your anserw it’s working well now :), i got 1 question. Is it posiible to make link. I mean for example i write Pol and as tip shows POLAND and after click on it i want it to go to some website.

  • dominique.jorandon

    Hi, I subscribed to your site but still wasnt able to get the download link. Please send me the code. dominique.jorandon@laposte.net THANK YOU so much

  • Sent 🙂

  • Yes Jacob,

    You can do using select: function( event, ui ) function of auto complete….

  • dominique.jorandon

    Thank you so much my friend for your link, very good work ! thx

  • Don

    I was looking for the code for Populate Mutiple Textbox with single auto-select Request. I subscribed but got no link.

  • Don
  • Jitender

    I want to use autocomplete
    But in a different way actually in your demo data comes out in a row .

    i want to first use autocomplete then on the basis of my selection i wan to fill columns like his dob, qualification mom dad and many more fields.

    Like you do in country demo.
    but this is in row .

    Is that its possible please let me know my email id is jitu.sorout@gmail.com …. Please Help me …

  • yes it’s possible, i sent download link to your mail. pls check

  • Mizael Morales

    gj i wanna know if u can help me to use this autocomplete to bring data and open files like pdf, thank you my email mizael754@gmail.com

  • venky perumalla

    can you send download link to my mail also .. if its possible..

  • Another

    Hi,
    i am subscribed your newsletter to get this files.
    Please kindly share tutorial files.

    Many thanks

  • Hi can you send me the source code?. Mail ID: altan@zirvebarkod.com

  • Ramesh

    how to add mouse events with this autocomplete….

  • motleychai

    Could you send me the code please? Thank you
    motleychai@gmail.com

  • Ankit

    Hi can you send me the source code?. Mail ID: ankitsumit1990@gmail.com

  • lusine

    I wanted the code for Populate Mutiple Textbox with single auto-select Request. I subscribed but got no link.
    Can you send me that one?

  • arshi

    Undefined index: type in C:wampwwwautoautocompleteajax.php on line 8 please help me…

  • This is perfect. How can I display a second field in the drop down along with the country?

  • HI Omar,

    Did u got source code, If you got then refer populate multiple textbox with single auto-select request script.

    tyr to send response like this [INDIA|356].

    Using success method assign Country id instead of name

    success: function( data ) {
    response( $.map( data, function( item ) {
    var code = item.split(“|”);
    return {
    label: code[0],
    value: code[1],
    data : item
    }
    }));
    }

  • you are missing type while making ajax request..

    data: {
    name_startsWith: request.term,
    type: ‘country_table’,
    row_num : row
    }

  • Perfect! But is there a way I can leave the textfield as is displaying the country name, but have the ID added into a hidden field?

  • yes, you can assign values to any number textfields using select method like this

    select: function( event, ui ) {
    var names = ui.item.data.split(“|”);
    $(‘#country_name ‘).val(names[0]);
    $(‘#country_id ‘).val(names[1]);
    }

  • How do i combine this method with the above method? When i try it I don’t see the value of the textfield populating in the other test textfield.

  • I got this to work but the problem is it adds the id once the dataset returns so it randomly picks and ID if there are multiple records returned.

    I need it to only add the ID selected by the user from the dropdown into the other textfield.

    so far my code is:

    success: function( data ) {
    response( $.map( data, function( item ) {

    var code = item.split(“|”);
    $(‘#thehiddentextfield’).val(code[1]);
    return {
    label: code[0],
    value: code[1],
    data : item
    }

    }

  • hi Omar,

    Refer my latest tutorial on this jquery autocomplete …

    http://www.smarttutorials.net/jquery-autocomplete-multiple-fields-using-ajax-php-mysql-example/

  • That did it!! Thank you. What an amazing tutorial!

  • Thank you 🙂

  • Is there a limit to the amount of records it’s returning. It seems to be cutting off at a certain point, not going through all the records?

  • Gera Vic

    can you send me the code please? i really need it, is for my final proyect! mi e-mail: keawe_01@hotmail.com

  • Gerardo Vicente Vicente

    your project is great broh! but i
    i want add more colums, how can do that?

  • yes, you can add no. colums required. but you need to change in your html page as well as juqery script… try, if u canot find out let me know…

  • there is no limit for the records…. pls check sql query, if u are limiting via limit….

  • Gerardo Vicente Vicente

    i was trying but i can’t, when i do that the values overlap in the same colum i try to change in your auto.js , ajax.php and index.php, i hope you can help me please! i want to add seven colums

  • Hi,

    pls change your table like this in index.php

    S. No
    Country Name
    Country Number
    Country Phone code
    Country code
    Favourite Place
    Historical Place
    Favourite Game

    1.

    Then chnage script in auto.js file

    var data=””+count+”.”;
    data +=” “;
    data += “”;
    data += ” “;
    data += ” “;
    data += ” “;
    data += “”;
    $(‘table’).append(data);

  • Gerardo Vicente Vicente

    thanks broh! i have problems with the auto,js i replace in the same order but dreamweaver say that exist a sintax error

  • I had sent modified source to your mail. Pls check…

  • Abhijit Pal

    Thanks a lot but you may also check this link http://abhijitpal.in/auto-suggestion-using-ajax-jquery-php/

  • Kwiclick Cyber-Lounge

    i appreciate if you sen me the DONWLOAD link of you amazing code. email me at info.kwiclick.ph@gmail.com. thank you

  • muni

    sent

  • parthiban

    i friend i need mutiple Textbox with single auto sugg
    please send me code for that
    my mail id
    v.parthi2@gmail.com

  • dennis

    dennis dickson

  • dennis

    I download autocomplete but I will not work on my computer using windows 8.1,Laravel, apache, php and MySQL. When I enter a letter nothing happens. Things I tried are as follows. I hear the field ‘name’ in the company table may be a problem so I changed to c_name. I change from MySQL to mysqli. I noticed auto.js was not in the script header so I added a link to it. My database name is busspir I set my connect to it as user ‘root’. My connection is good because I have other methods using it and I get no errors. When I changed to mysqli I added the $con to the select statement and changed all the references of MySQL to mysqli. Please help me I have become a member of Smart Tutorials and intend to use it exclusively.

  • Hi Dennis,

    When type something in text box, Is it make ajax request?
    If ajax request goes then check what value you in php?
    Then finally check what SQL query it generates?

  • dennis

    Thank you for the response. I’m new at this so how do I check the ajax request and the query.

  • Denis if you are Firefox browser then install firebug extension .. Then launch that using F12… When type something it make ajax to server … You see that in the console window… On php side just echo the query , you will get response as that query ….

  • Haruna Ahmadu

    please how can i add a href to the data from database

  • I´m looking for the code Populate Multiple Textbox with single auto-select Request just like you have. I subscribed but got no link and I get subscribed but nothing happens. Thanks this is my mail: elimelecmunoz[at]gmail.com

  • rushi

    how to download above code

  • you need subscribe the blog…

  • rushi

    I had already subscribe it…

  • Yuta Lolap

    HI all,

    Facing issue with the following code. I have followed the instructions mentioned above but still i cant seem to detect it. ajax call is scene in the firebug console, but it always returns the alert from the error call function.

    <?php

    include 'config.php';
    include 'connection.php';

    $('#project_id').autocomplete({
    source: function( request, response ) {
    $.ajax({
    url : 'autopopulate.php',
    dataType: "json",
    data: {
    name_startsWith: request.term,
    type: 'project_id'
    },
    success: function( data ) {
    alert('sucess');
    console.debug(data);
    response( $.map( data, function( item ) {
    return {
    label: item,
    value: item
    }
    }));
    },
    error:function(){

    alert('error');
    }
    });
    },
    autoFocus: true,
    minLength: 0
    });

    if($_GET['type'] == 'project_id'){
    $sql ="Select project_id from ".$tbl_prefix."project_directory where project_id like '".$_GET['name_startsWith'])."%'";
    echo $sql;
    $result = mysqli_query($con,$sql) or die(mysqli_error());

    $data = array();
    while ($row = mysqli_fetch_array($result)) {
    array_push($data, $row['project_id']);
    }
    echo json_encode($data);

    }
    Please can you guys tell me where i might be going wrong? Is this any version specific issues?

  • prince

    any help 😀
    its not working 🙁

  • prince

    where can i get the full code of this tutorial

  • waheed

    waheed_z89@yahoo.com
    i already subscribed .. i need this code thnx

  • Can someone email me the file? I already subscribe but i don’t receive it

  • Guestt

    Pls send me this script code.. ernestrajkumar@gmail.com

  • Aby

    I subscribed yesterday and got a message that i would get the link to download the code in the next 12 hrs, but still nothing, can you send me the link to abby.cid@gmail.com please? I am new in all this so i really want to study your code, it looks awesome what it does.

  • Agu Derregibus

    no me ha llegado nada. Me lo pueden enviar al mail ?
    laventasegura@gmail.com
    Gracias

  • Mansa Rao

    Hi can u please suggest me how to get ajax variable to php variable on same page

  • shilpa

    hi your example is perfect for me to work with autocomplete but i am unable to connect according to my database .can anybody suggest me to connect

  • shilpa

    hey i done it.. thank you

  • ram dhana

    how???????
    my mail id
    dhanasekarancse008@gmail.com

  • yeremia

    I had already subscribe. can you send me the link to yeremiayuliyanto40@gmail.com

  • aditakumar

    not working auto complete in server

  • vivek

    i already subscribed but not able to download..:-(

  • Kumar Patil

    hi shilpa
    can you provide me this code at kumar_635@rediff.com

  • ADITYA SHANKER

    Hey can some one mail me the source code.. I have already subscribed but didnt get the source code
    my id is – f2011244@dubai.bits-pilani.ac.in

  • Rakesh Choyal

    can u plzzz provide me the code … thanks in advance . i need it for my college website
    email id:- rakeshchoudhry.224@gmail.com

  • Rakesh Choyal

    its a humble request plzz provide the code
    email id:- rakeshchoudhry.224@gmail.com

  • agata

    Hello everybody, I tested this code, but I got error that autocomplete function is not a function. Do you know why? I change jquery version but doesn’t work. Can you help me?

  • Sachin Chaudhary

    Hi Shilpa.
    Can u share this code with me at sachinpanwar1000@gmail.com

  • Hely Rojas

    Great tutorial.

    I just implement it on my page: http://paginas-amarillas.avisus.net

    I modified the CSS to highlight the search term.
    I no use Json.

  • Tenisha Rai

    This is the best autocomplete tutorial. Thank u very much.

  • Shekhar

    Hey Can Somebody send me this link to download the code shekhardt@gmail.com

  • joan

    can you please email me the script joanna.pantua@gmail.com thanks. got no link but i already subscribed

  • Thanks,

  • Eko Fernando

    how to download above code please help me

Get Instant Script Download Access!