PHP-MySQL Ajax Jquery-UI Autocomplete in Bootstrap

Furqan Aziz | 18 Oct 2013 | Tutorials

PHP-MySQL Ajax Jquery-UI Autocomplete in Bootstrap

Introduction

You will learn to make Jquery UI autocomplete working in Bootstrap via PHP, MySQL and Ajax.PHP-MySQL Ajax Jquery-UI Autocomplete in Bootstrap tutorial is about Jquery UI (User Interface) Autocomplete usage in Bootstrap via PHP, MySQL and AJAX. It will make search function easy and user-friendly. User begins typing the characters and if results match with stored data it will be shown straight away below the search field. We will learn

Source Files and Folders Explanation

Available source has below PHP Pages, Text File and Folders for your reference. Below is summary of each.

    Create Table and Sample Data

  1. Let's Start. Download source file and unzip it then create category table in your database using sql.txt code.
    • category table contains categories and sub categories.
    • CREATE TABLE IF NOT EXISTS `category` (
        `SrNo` int(11) NOT NULL AUTO_INCREMENT,
        `Category` varchar(50) NOT NULL,
        `SubCategory` varchar(100) NOT NULL,
        PRIMARY KEY (`SrNo`)
      ) ENGINE=MyISAM  DEFAULT CHARSET=latin1
      -- Dumping data for table `country`
      INSERT INTO `category` (`SrNo`, `Category`, `SubCategory`) VALUES
      (1, 'Electronics', 'Mobile'),
      (2, 'Electronics', 'Tablet'),
      (3, 'Electronics', 'IPad'),
      (4, 'Electronics', 'ITab'),
      (5, 'Electronics', 'Television'),
      (6, 'Electronics', 'Camera'),
      (7, 'Electronics', 'Laptop'),
      (8, 'Electronics', 'LCD'),
      (9, 'Electronics', 'Computer'),
      (10, 'Books', 'Magazines'),
      (11, 'Books', 'Journals'),
      (12, 'Books', 'Course Books'),
      (13, 'Garments', 'Kids Clothes');

    Connect to Database

  2. Now we will create configPDO.php file and use PDO (PHP Data Objects) for connecting MySQL Database.
    • <?php
      // mysql hostname
      $hostname = 'localhost';
      // mysql username
      $username = 'root';
      // mysql password
      $password = '';
      // Database Connection using PDO with Try Catch Statements
      try {
      $dbh = new PDO("mysql:host=$hostname;dbname=YOURDATABASENAME", $username, $password);
          }
      catch(PDOException $e)
          {
          echo $e->getMessage();
          }
      ?>

    Demo Page Explanation

  3. Now we will create demo.php in which we will create search field, search button, Categories in table, Jquery Ajax Function and all required links of Jquery UI in bottom of page.
  4. Include Connection

    First we will include configPDO.php on first line of the page.

    • <?php  include('configPDO.php'); ?>

    Make Search Form

    Now we will make a form inside bootstrap container. Here searchg is id of search field which is refer in jquery ajax function for showing search terms.

    • <form method="post" class="navbar-form pull-left" action="Searchcategory.php" >
      <input class="span4" id="searchg" name="searchg" type="text" placeholder="Search">
      <button class="btn" type="submit">Search</button>
      </form>
      

    Include Jquery UI Files

    Now include following Jqury UI files before the </body> tag inside your demo.php page. These files are in ui folder which is inside assets folder of available source file.

    • <!--Jquery UI required links-->
      <script src="assets/ui/jquery.ui.core.js"></script>
      <script src="assets/ui/jquery.ui.widget.js"></script>
      <script src="assets/ui/jquery.ui.position.js"></script>
      <script src="assets/ui/jquery.ui.menu.js"></script>
      <script src="assets/ui/jquery.ui.autocomplete.js"></script>

    Include CSS File for Jquery UI

    For style and beauty put following Jquery UI css link before the </head> tag.

    • <!--Jquery UI css link-->
      <link rel="stylesheet" href="assets/ui/themes/ui-darkness/jquery.ui.all.css">
      

    Jquery Ajax Function

    Under Jquery UI required links write following Ajax code for showing auto complete on search field. Here url is the page name where data get using JSON data type. searchg is id of search field in which search suggestions will display. Get_Auto1.php is a page which contains JSON results.

    • <script type="text/javascript">
      // Code inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
      $(document).ready(function()
      {
      // Perform an asynchronous HTTP (Ajax) request.
      $.ajax({
      // A string containing the URL to which the request is sent.
          url: 'Get_Auto1.php',
      //The type of data that you're expecting back from the server.
          dataType: 'json',
      //Function for showing data in search field.    
          success: function(data){
          $('#searchg').autocomplete(
          {
          source: data,
          minLength: 1    
          });
          }
                });
      		  
      });
      </script>

    Get Auto Page Explanation

  5. Get_Auto1.php page you will write following code to get results from database and output JSON String.
    • <?php
      // Database Connection
      include("configPDO.php");
      // Query to get the usable suggestions
      	$likeString = '%' . $_GET['term'] . '%';
      // We Will prepare SQL Query
          $STM = $dbh->prepare("SELECT DISTINCT  Category FROM category WHERE Category LIKE :likeString");
      // bind parameters, Named parameters always start with colon(:)
          $STM->bindParam(':likeString', $likeString);
      // For Executing prepared statement we will use below function
          $STM->execute();
      // we will fetch records like this and use foreach loop to show multiple Results
          $STMrecords = $STM->fetchAll();
      // Deifne array for category.
      	$Category_array = array();
      // Use for each loop to push all results in category array.
      foreach($STMrecords as $row)
      {
      // Store all values in $result variable.
      $result = $row[0];
      // push all values in category array using array_push function which treats array as a stack, and pushes the passed variables onto the end of array.
      array_push($Category_array, $result);	
      }
      // encode it using json_encode which returns a string containing the JSON representation of value.		
      $json = json_encode($Category_array);
      // echo it for getting it using Ajax function explained above.
      echo $json;          
      ?>

    Search Result Page Explanation

  6. In Searchcategory.php page write following code inside the body tag.
    • <?php
      // if there is nothing in search box, show error like this using bootstrap alert error.
      if($_POST[searchg]=='')
      {
      echo"<div class='alert alert-error'>";
      echo"<button type='button' class='close' data-dismiss='alert'>×</button>";
      echo"<p>Please write correct Category  in Search box and Click Search!</p>";
      echo"</div>";
      }
      // if something search show info alert and show results in table like below.
      else
      {
      echo"<div class='alert alert-info'>";
      echo"<button type='button' class='close' data-dismiss='alert'>×</button>";
      echo"<p>You search for <strong>$_POST[searchg]</strong></p>";
      echo"</div>";
      // Start of table
      echo"<table class='table table-bordered table-hover'>";
                    echo"<thead>";
                      echo"<tr>";
                        echo"<th>Sr#</th>";
                        echo"<th>Category</th>";
                       echo" <th>Sub Category</th>";
                      echo"</tr>";
                    echo"</thead>";
                    echo"<tbody>";
      // Define variable and store search query in it.
      	$searchg = $_POST['searchg'];
      // Prepare query for showing requested results.
          $STM = $dbh->prepare("SELECT `SrNo`, `Category`, `SubCategory` FROM category WHERE Category LIKE :searchg");
      // bind paramenters, Named paramenters alaways start with colon(:)                      
          $STM->bindParam(':searchg', $searchg);
      // For Executing prepared statement we will use below function
          $STM->execute();
      // // fetch records like this and use foreach loop to show multiple Results
          $STMrecords = $STM->fetchAll();
          foreach($STMrecords as $row)
              {
      		 echo"<tr>";
               echo"<td>".$row[0]."</td>";
      		 echo"<td>".$row[1]."</td>";
      		 echo"<td>".$row[2]."</td>";
               echo"</tr>";
              }		
                    echo "</tbody>";
                  echo "</table>";
      }
      ?>

Conclusion

Hope you find this tutorial very easy and user-friendly. PHP-MySQL Ajax Jquery-UI Autocomplete in Bootstrap tutorial is very useful for making Auto-complete function in web pages. In this tutorial we use Jquery UI autocomplete and Bootstrap 2.3.2 together. Now bootstrap lovers can use auto search functionality in their bootstrap projects. For any query/suggestions please send message on our Facebook Page. Thanks :)

Social Box

LATEST TUTORIALS
PHP MySQL Simple Delete using PDO in Bootstrap Tutorial
Convert Simple Text To 3D Text using Adobe Fireworks CS6 Tutorial
PHP Simple Update using PDO in Bootstrap Tutorial
PHP Simple Insert using PDO in Bootstrap Tutorial
PHP MySQL Easy CSV Data Insertion in Bootstrap using PDO Tutorial
PHP Easy Sign-in Using PDO Prepared Statement Tutorial
Easy PHP Email With Attachments using Swift Mailer Tutorial
Easy Pagination with PDO in PHP plus Export to Excel Tutorial
PHP PDO to Connect MySQL Database Tutorial
Best CSS Frameworks Collection For Rapid Web Development
PHP-MySQL Ajax Jquery-UI Autocomplete in Bootstrap Tutorial
PHP Simple Sign-in Tutorials
Jquery Raty Usage via PHP
PHP Dynamic Select options Via Ajax
CSV Importer in MySQL
PHP File Load Via Jquery into DIV
PHP Simple Delete using PDO in Bootstrap Tutorial Convert Simple Text To 3D Text using Adobe Fireworks CS6 Tutorial PHP Simple Update using PDO in Bootstrap Tutorial PHP Simple Insert using PDO in Bootstrap Tutorial PHP MySQL Easy CSV Data Insertion in Bootstrap using PDO Tutorial PHP Easy Sign-in Using PDO Prepared Statement Tutorial Easy PHP Email With Attachments using Swift Mailer Tutorial Easy Pagination with PDO in PHP plus Export to Excel Tutorial PHP PDO to Connect MySQL Database Tutorial Best CSS Frameworks Collection For Rapid Web Development PHP-MySQL Ajax Jquery-UI Autocomplete in Bootstrap Tutorial PHP Simple Sign-in Tutorials Jquery Raty Usage via PHP PHP Dynamic Select options Via Ajax CSV Importer in MySQL PHP File Load Via Jquery into DIV Query plus Grant Privileges Tutorial PHP Easy Installation Tutorial PHP Simple Mail Form Tutorial 15 Best Fireworks Tutorials CSS Layout Basic Tutorial PHP Ajax Live Search Tutorial
© 2014 CreWow Network - All Rights Reserved.