Autocomplete in jQuery using PHP and MySQL – a beginner tutorial

Spread the love

Autocomplete in jQuery

Modern web applications often use auto suggest feature in forms. In this tutorial, you will learn autocomplete in jquery using php and MySQL.

In this tutorial, following steps will be done.

  • Setup the application
    • Create application folder
    • Install composer
    • Create project folder structure
  • Create a MySQL database
  • Create a HTML form for autocomplete in jquery
  • Create Database class to perform database operations
  • Add a script to accepts search term, returns the results
  • Display the matched results
  • Run the application

autocomplete in jquery with php and mysql

1. Setup the application

You should have PHP, MySQL and phpMyAdmin installed on your system. Install XAMPP or WAMP. After installation, start Apache, MySQL services.

  • Create application folder

Create a folder autocomplete-in-jquery inside the www or htdocs folder in WAMP or XAMPP. Open command line. Go to the application folder, write the command:

cd autocomplete-in-jquery
  • Setup using composer

Download and install composer with default wizard instructions. Type the command.

composer init

Composer.json file is generated. Replace the code in the composer.json file.

{
    "autoload": {
      "psr-4": {
        "App\\": "src/"
      }
    }
}

See the “App\\”: “src/” line in composer.json.

Installing required dependencies.

On command line, type command below.

composer install

PSR-4 autoload package is installed.

“Namespace” is App and src is the folder, where database and fetch_records_ajax.php files are saved. Vendor folder and composer.lock file is also generated.

Creating project directory structure

Open the project folder and create these directories.

  • Create src folder
  • Create inc folder
  • Create assets folder, inside inc folder
  • Create css folder inside inc folder

autocomplete jquery

Let’s create database and HTML form after setting up the folder structure.

2. Create a MySQL database

Open PhpMyAdmin and add a database named dbbookstore.

http://localhost/phpmyadmin

Open SQL Tab, and run the command.

CREATE DATABASE dbbookstore;

Books table will have following fields:

  • Id
  • title
  • author_name
  • price
  • ISBN
  • category

Create a table books, running the CREATE TABLE command in SQL tab of phpMyAdmin.

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(500) NOT NULL,
  `author_name` varchar(500) NOT NULL,
  `price` varchar(500) NOT NULL,
  `ISBN` varchar(50) NOT NULL,
  `category` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

Insert data into the database

INSERT INTO `books` VALUES (1,'C++ By Example','John','500','PR-123-A1','Programming'),
  (2,'Java Book','Jane davis','450','PR-456-A2','Programming'),
  (3,'Database Management Systems','Mark','300','DB-123-ASD','Database'),
  (4,'Harry Potter and the Order of the Phoenix','J.K. Rowling','650','FC-123-456','Novel'),
  (5,'Pride and Prejudice','Jane Austen','450','FC-456-678','Novel'),
  (6,'Learning Web Development ','Michael','300','ABC-123-456','Web Development'),
  (7,'Professional PHP & MYSQL Web Development','Author 2','340','PR-123-456','Web Development'),
  (8,'Professional Java Web Development','Author','300','PR-123-488','Web Development');
  (9,'Professional ASP.NET Web Development','Example','300','PR-123-888','Web Development');

autocomplete in jquery using php and mysql

2. Create HTML files

Let’s create header, footer and index.php files.

Create header.php file

Open inc folder, add a file header.php.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700">
<title>Autocomplete in jquery Using PHP and MySQL</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="inc/assets/css/style.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>

In header.php file, the CSS and JavaScript files are included.

Add a style.css file

Open css folder inside inc folder in assets folder. Add file style.css.

body {
  color: #fff;
  background: #63738a;
  font-family: 'Roboto', sans-serif;
}
.form-control {
  height: 40px;
  box-shadow: none;
  color: #969fa4;
}
.form-control:focus {
  border-color: #5cb85c;
}
.form-control, .btn {        
  border-radius: 3px;
}
.signup-form {
  width: 450px;
  margin: 0 auto;
  padding: 30px 0;
    font-size: 15px;
}
.signup-form h2 {
  color: #636363;
  margin: 0 0 15px;
  position: relative;
  text-align: center;
}
.signup-form h2:before, .signup-form h2:after {
  content: "";
  height: 2px;
  width: 30%;
  background: #d4d4d4;
  position: absolute;
  top: 50%;
  z-index: 2;
}  
.signup-form h2:before {
  left: 0;
}
.signup-form h2:after {
  right: 0;
}
.signup-form .hint-text {
  color: #999;
  margin-bottom: 30px;
  text-align: center;
}
.signup-form form {
  color: #999;
  border-radius: 3px;
  margin-bottom: 15px;
  background: #f2f3f7;
  box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
  padding: 30px;
}
.signup-form .form-group {
  margin-bottom: 20px;
}
.signup-form input[type="checkbox"] {
  margin-top: 3px;
}
.signup-form .btn {        
  font-size: 16px;
  font-weight: bold;    
  min-width: 140px;
  outline: none !important;
}
.signup-form .row div:first-child {
  padding-right: 10px;
}
.signup-form .row div:last-child {
  padding-left: 10px;
}      
.signup-form a {
  color: #fff;
  text-decoration: underline;
}
.signup-form a:hover {
  text-decoration: none;
}
.signup-form form a {
  color: #5cb85c;
  text-decoration: none;
}  
.signup-form form a:hover {
  text-decoration: underline;
}

Create footer.php file

In inc folder, add a file footer.php and add code.

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
    $( function() {
        $( "#search" ).autocomplete({
            source: function (request, response) {
                $.get("src/fetch_records_ajax.php", 
                {
                    data: request,
                    dataType: "json"
                })
                .done(function( data ) {
                    data = $.parseJSON(data);
                    response(data);
                });
            }
        }, {
            minLength: 1,
        });
});
</script>
</body>
</html>

In footer.php file jQuery and jQueryUI files are included. In document.load method $( function() { .. }); text field #search is created as autocomplete field.

The source method in autocomplete is used to get records and display in a drop down. An AJAX request is sent to src/fetch_records_ajax.php file and in .done() method JSON parsed data is assigned to data is passed to response() method.

Create index.php file

Open project folder. Create a file index.php.

<?php include_once('inc/header.php'); ?>
<div class="signup-form">
    <form method="post" action="index.php" enctype="multipart/form-data">
    <h5>Autocomplete in jquery with PHP & MySQL</h5>
    <p class="hint-text"></p>
      <div class="form-group">
         <div class="ui-widget">
            <label for="tags">Type book name:</label>
            <input id="search" size="50" placeholder = "e.g web development">
         </div>`
    </div>
    </form>
</div>
<?php include_once('inc/footer.php'); ?>

autocomplete jquery

 

In index.php file, a form is created with a text field search is added for autocomplete feature.

3. Create scripts for autocomplete in jquery tutorial

Let’s add classes in autocomplete in jquery tutorial. Open the project folder in IDE like Visual Studio Code.

Create Database.php class

Create a file Database.php in src folder, and open it in the editor and add the code.

<?php 

namespace App; 

use PDO;

class Database
{
    private $host;
    private $user;
    private $password;
    private $database;
    private $dbconn;
    
    function __construct()
    {
        $this->host = 'localhost';
        $this->user = 'root';
        $this->password = '';
        $this->database = 'dbbookstore';
        $this->dbconn = null;
    }

    public function connect()
    {
        try {
            $this->dbconn = new PDO('mysql:host='.$this->host.';dbname='.$this->database.'', $this->user, $this->password) or die("Cannot connect to MySQL.");
            // set the PDO error mode to exception
            $this->dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            //echo "Database connected successfully";

            return $this->dbconn;
        } catch(PDOException $e) {
            echo "Database connection failed: " . $e->getMessage();
            die();
        }
    }

    /** Get books records from database for autocomplete */
     public function fetch($term) {
        $this->connect();
        $sth = $this->dbconn->prepare( "SELECT title FROM books WHERE `title` like ?");
        $sth->bindValue(1, "%$term%", PDO::PARAM_STR);
        $sth->execute();
        $result = $sth->fetchAll();        
        $this->dbconn = null;

        return $result;
    }
}

In class constructor the database credentials are initialized. In connect method, database connection is created using PDO (php data objects) library.

Next, is fetch method that accepts the user entered term as parameters. In this method, database connection is created.

And the books records are selected from books table, where titles are related to the user’s term. After query execution all the results are assigned to $result array.

Create jQuery Ajax script to fetch results

Create a script fetch_records_ajax.php in src folder.

<?php
    namespace App;
    
    use App\DB;

    include_once('../vendor/autoload.php');
    $db = new Database();
    $result = [];

    if(isset($_GET['data']['term'])) {
        $term = $_GET['data']['term'];
        $books = $db->fetch($term);
        foreach($books as $key => $book) {
            array_push($result, $book['title']);
        }
    } else {
        $result['status'] = 400;
        $result['message'] = 'Enter a search term';
    }

    echo json_encode($result);

In the script database object is created and assigned to $db. User entered search term assigned to $term and passed to $db‘s  fetch method, the results are assigned to $books.

Book titles are assigned to $result array in foreach loop and returned to front end. In front end the matching results are displayed.

autocomplete in jquery using php and mysql with composer

Running the application

In order to run the application, make sure Apache and MySQL services are running. Open the browser, type the URL in address bar.

http://localhost/autocomplete-in-jquery/

Summary:

In this tutorial, you have learned to create an autocomplete in jQuery with php and MySQL. Database table is created and a form and jQuery script is added to get auto suggest drop down for user entered value.

Source code of tutorial:

You can find the source code of the tutorial on our GitHub Repository. Clone or download the project in htdocs or www root folder and run in browser.

If you liked this tutorial, subscribe to our newsletter and follow us on Twitter, or like our Facebook page.

 

Related Articles:

Previous Article:

 

Next Article:

 

 

Check Also

How to use arrow functions in javascript

Introduction to arrow functions in javascript

Spread the loveLast updated:6th November, 2021Arrow functions in JavaScript Arrow function were introduced in ES6 …