, , , , ,

jQuery Autocomplete Search using PHP, MySQL and Ajax

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 search box like in google search box. I had implemented two types of…

147
jQuery Autocomplete using PHP, MySQL and Ajax

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

I have released series of tutorial on jQuery UI autocomplete right from the scratch, Please check here jQuery UI Autocomplete Video Tutorials

Learn jQuery Autocomplete in 3 Minutes

jQuery Autocomplete With Dynamic JSON Data from PHP, Ajax and MySQL Database

jQuery Autocomplete – Show No Record Found

 

 

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. Also kept two database utility functions to prepare prepared statements and get results from executed query.

<?php
/**
 * File config.php
 * @author muni
 * @link https://smarttutorials.net/
 */

define('BASE_PATH', 'http://localhost/demo_tut/jquery-autocomplete/');
define('DB_HOST', 'localhost');
define('DB_NAME', 'smarttut_demo');
define('DB_USER','xyz');
define('DB_PASSWORD','mysql');

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
    exit();
}

// $sql = "SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))";
// $mysqli->query($sql);

/**
 * Preparing Statement
 */
function prepareStatement($sql, $params = null)
{
    global $mysqli;
    $stmt = $mysqli->prepare($sql);
    if (!($stmt)) {
        throw new Exception("Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);
    }

    if (!empty($params) && is_array($params)) {
        $count = count($params);            
        $bindStr = str_repeat('s', $count);
        $stmt->bind_param($bindStr, ...$params);
    }

    if (!$stmt->execute()) {
        throw new Exception("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
    }

    return $stmt;
}

/**
 * GetResult
 */
function getResult($stmt)
{
    if (!($res = $stmt->get_result())) {
        throw new Exception("Getting result set failed: (" . $stmt->errno . ") " . $stmt->error);
    }
    return $res;
}

Step 3:

Now create index.php file and add the 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 make ajax request to the server with user entered data in textbox. Finally get the response from the server and shows as suggestions.


$("#country_name").autocomplete({
    source: function(data, cb){
        $.ajax({
            url: 'ajax.php',
            method: 'GET',
            dataType: 'json',
            data: {
                name: data.term
            },
            success: function(res){
                var result;

                result = [
                    {
                        label: 'There is matching record found for '+data.term,
                        value: ''
                    }
                ];

                if (res.length) {
                    result = $.map(res, function(name){
                        return {
                            label: name,
                            value: name
                        };
                    });
                }

                cb(result);
            }
        });
    }
});

Step 6:

Create ajax.php and functions.php files. Where ajax.php will get client request and make appropriate function call in functions.php to get response.

<?php
/**
 * @filename ajax.pgp
 * @link https://smarttutorials.net/
 * @author muni
 */
require_once 'config.php';
require_once 'functions.php';
$data = [];
if ($_GET['type'] == 'country') {
	$data = getCountryList($_GET);
}
<?php
/**
 * @file functions.php
 * @author muni
 * @link https://smarttutorials.net/
 */

function getCountryList($data)
{
    $name = strtoupper($data['country_name']);
    $name = $name.'%';
    $sql = "SELECT name FROM country where UPPER(name) LIKE ? limit 25";
    $stmt = prepareStatement($sql, [$name]);
    $res = getResult($stmt);
    return $res->fetch_all(MYSQLI_ASSOC);
}

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

147 responses to “jQuery Autocomplete Search using PHP, MySQL and Ajax”

  1. eric fan

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

  2. Prince

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

  3. sethu

    hi,
    can u email me this coding.
    To: [email protected]

    thnx in advance

  4. nilesh

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

  5. Plz send to my mail id ….

  6. hi,
    can u email me this coding.
    To: [email protected]

    thnx in advance

  7. brijesh

    dear mumi, can you send me “Populate Mutiple Textbox with single auto-select Request” project file.
    at
    [email protected]

  8. Lan

    Can i have fullsource this examples, my email is: [email protected]

  9. JulioS

    Dear Mumi, u can send to me email with this code at [email protected]
    Tks!

  10. Anand

    Can you email me the code,

    Very helpfull code.

    Thanks in advance..

  11. muni

    Sent

  12. muni

    sent

  13. muni

    sent ๐Ÿ™‚

  14. aljadek

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

    Thx

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

    [email protected]

    thank you

  16. Balaji

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

  17. Pulkit

    Hey can u mail me full source code for this.
    Thanks ๐Ÿ™‚

  18. 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: [email protected]

    Thanks

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

  20. Ezio

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

  21. dasa

    Hi Muni… nice code there… can you email me the code
    thanks in advance ๐Ÿ˜‰

  22. muni

    sent ๐Ÿ™‚

  23. muni

    sent ๐Ÿ™‚

  24. muni

    sent ๐Ÿ™‚

  25. shendi

    Can you mail me the code sir, thanks before. ๐Ÿ™‚ [email protected]

  26. Rajesh kannan

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

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

  28. hendi

    Hi..
    sorry before…
    can you email me the code
    thanks and databese….?? to [email protected]

  29. Hendi

    Hi..
    Can You email Code And Database To My Email…??
    [email protected]

  30. Aswin K M

    Please mail me the code @ [email protected]… Thanks in advance.

  31. longdonkey19

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

    regards

  32. Igor

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

  33. ashish

    please send the code to my mail.
    my email is : – [email protected].
    its very urgent .
    thanks in advance ๐Ÿ˜‰

  34. kumara

    hi
    can u email me this coding
    to : [email protected]

    thanks

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

  36. kamal

    good

  37. sachin

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

    [email protected]

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

  39. Joe

    Hi Muni,

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

  40. sirshendu ghosh

    please send the code to my mail.”Populate Mutiple Textbox with single auto-select Request” My email id is [email protected]

  41. Raffles

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

  42. fon

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

  43. fon

    please send the code to my mail. thanks in advance : [email protected]

  44. Adeel

    Could you please send me the code on [email protected]

  45. mohit

    Hi Muniโ€ฆ nice code thereโ€ฆ gud job..

  46. mounika

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

  47. ramki

    Hi could you mail me source code please ๐Ÿ™‚

  48. ramki

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

    Thx

  49. irwan

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

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

  51. Vijay Chauhan

    Can you send me these code ??

    its very nice !!

    [email protected]

  52. paul

    Would appreciate the source code. My email is [email protected]. Thanks.

  53. wojtek

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

  54. I am still waiting for the sql ๐Ÿ™

  55. Kem

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

    Thanks

  56. Arvind

    Hi Can I too have the full source…
    Mail Id: [email protected]

  57. Arvind

    Hi can you send me the source code. Mail ID: [email protected]

  58. muni

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

  59. Hindujhan

    Can you please email this coding to my email

  60. subbu vemuri

    Hi can you send me the source code. Mail ID: [email protected]

  61. rocky

    send me plz

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

  63. 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 ๐Ÿ™‚

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

  65. dominique.jorandon

    Hi, I subscribed to your site but still wasnt able to get the download link. Please send me the code. [email protected] THANK YOU so much

  66. Sent ๐Ÿ™‚

  67. Yes Jacob,

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

  68. dominique.jorandon

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

  69. Don

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

  70. 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 [email protected] …. Please Help me …

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

  72. 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 [email protected]

  73. venky perumalla

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

  74. Another

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

    Many thanks

  75. Hi can you send me the source code?. Mail ID: [email protected]

  76. Ramesh

    how to add mouse events with this autocomplete….

  77. motleychai

    Could you send me the code please? Thank you
    [email protected]

  78. Ankit

    Hi can you send me the source code?. Mail ID: [email protected]

  79. 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?

  80. arshi

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

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

  82. 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
    }
    }));
    }

  83. you are missing type while making ajax request..

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

  84. 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?

  85. 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]);
    }

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

  87. 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
    }

    }

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

  89. Thank you ๐Ÿ™‚

  90. 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?

  91. Gera Vic

    can you send me the code please? i really need it, is for my final proyect! mi e-mail: [email protected]

  92. Gerardo Vicente Vicente

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

  93. 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…

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

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

  96. 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);

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

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

  99. Abhijit Pal

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

  100. Kwiclick Cyber-Lounge

    i appreciate if you sen me the DONWLOAD link of you amazing code. email me at [email protected]. thank you

  101. parthiban

    i friend i need mutiple Textbox with single auto sugg
    please send me code for that
    my mail id
    [email protected]

  102. dennis

    dennis dickson

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

  104. 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?

  105. dennis

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

  106. 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 ….

  107. Haruna Ahmadu

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

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

  109. rushi

    how to download above code

  110. you need subscribe the blog…

  111. rushi

    I had already subscribe it…

  112. 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?

  113. prince

    any help ๐Ÿ˜€
    its not working ๐Ÿ™

  114. prince

    where can i get the full code of this tutorial

  115. waheed

    [email protected]
    i already subscribed .. i need this code thnx

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

  117. Guestt

    Pls send me this script code.. [email protected]

  118. 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 [email protected] please? I am new in all this so i really want to study your code, it looks awesome what it does.

  119. Agu Derregibus

    no me ha llegado nada. Me lo pueden enviar al mail ?
    [email protected]
    Gracias

  120. Mansa Rao

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

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

  122. shilpa

    hey i done it.. thank you

  123. ram dhana

    how???????
    my mail id
    [email protected]

  124. yeremia

    I had already subscribe. can you send me the link to [email protected]

  125. aditakumar

    not working auto complete in server

  126. vivek

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

  127. Kumar Patil

    hi shilpa
    can you provide me this code at [email protected]

  128. ADITYA SHANKER

    Hey can some one mail me the source code.. I have already subscribed but didnt get the source code
    my id is – [email protected]

  129. Rakesh Choyal

    can u plzzz provide me the code … thanks in advance . i need it for my college website
    email id:- [email protected]

  130. Rakesh Choyal

    its a humble request plzz provide the code
    email id:- [email protected]

  131. 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?

  132. Sachin Chaudhary

    Hi Shilpa.
    Can u share this code with me at [email protected]

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

  134. Tenisha Rai

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

  135. Shekhar

    Hey Can Somebody send me this link to download the code [email protected]

  136. joan

    can you please email me the script [email protected] thanks. got no link but i already subscribed

  137. Eko Fernando

    how to download above code please help me

  138. Haripriya palaniswamy

    Can someone mail me the entire source code to [email protected]

  139. Hans Raj

    can please send me entire working source code to [email protected] ,as above code is not working

  140. Krishan Kumar

    how do i highlight text in it.

  141. Amit Mishra

    Can you Also post how to Edit and update the same using jquery autocomplete? If possible,please provide that too in your tutorial series.

Leave a Reply