jQuery Autocomplete Search using Ajax, MySQL and PHP


jQuery Autocomplete Search using Ajax, MySQL and PHP







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`;
JavaScript
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 ;
JavaScript
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 ;
JavaScript
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 : phpcable.com
Author :Erick Kennedy Sakala
*/
define('DB_HOST', 'localhost');
define('DB_NAME', 'autocomplete');
define('DB_USER', 'root');
define('DB_PASSWORD', 'mysql');

$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
} 
JavaScript
Step 3:
Now create index.php file and create following textbox.
<input id="country_name" class="form-control txt-auto"/>
JavaScript
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>
JavaScript
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(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);
            }
        });
    }
});
JavaScript
Step 6:
create ajax.php file that will handle all ajax request from the client.

<?php
/*
Site :  phpcable.com
Author :Erick Kennedy Sakala
 */
require_once 'config.php';

$data = array();
if (!empty($_GET['name'])) {
    $name = strtolower(trim($_GET['name']));
    $sql = "SELECT name FROM country where LOWER(name) LIKE '" .$name. "%'";
    $result = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_assoc($result)) {
        array_push($data, $row['name']);
    }
}
echo json_encode($data);exit;
JavaScript
Please download source code(added all example code showed in the demo page)  of this tutorial using above download link.

Post a Comment

0 Comments