Typeahead Implementation in PHP/MySQL

First, you need to include all the necessary files for this to work. Place these three files in the head section of your page..

  • jquery-1.10.2.min.js 
  • bootstrap.min.js
  • bootstrap3-typeahead.min.js

Then, this script:

$(document).ready(function () {
    var objects = [];
    var map = {};
        source: function (query, process) {
                url: 'get_person.php',
                type: 'POST',
                dataType: 'JSON',
                async: true,
                success: function (data) {
                    objects = []; //resets the objects 
                    map = {}; //to avoid duplication
                    $.each(data, function (i, object) {
                        map[object.full_name] = object;
        }, //end source
        updater: function (item) {
            return item;
    }); //end of person typeahead
    $('#person').focus(function () {

This is my PHP code in which it passes a JSON object to my index.php file.

header('Content-Type: application/json');
 $query = mysqli_query($GLOBALS["___mysqli_ston"], "select userid,title,first_name, middle_name, last_name from tblperson;");
 $array = array();
 while($row = mysqli_fetch_array($query))
     $userid = $row['userid'];
  $title = $row['title'];
  $fname = $row['first_name'];
  $mname = substr($row['middle_name'],0,1);
  $lname = $row['last_name'];
  $data[$i]['userid'] = $userid;
  $data[$i]['fname'] = $fname;
  $data[$i]['mname'] = $mname;
  $data[$i]['lname'] = $lname;
  $data[$i]['full_name'] = $title.$fname." ".$mname."."." ".$lname;
 echo json_encode($data);

Just click the DEMO link above then copy the JavaScript source.

Popular posts from this blog

Add/Subtract Single Digit Number in Assembly Language

Set table width to 100% on PDF export in Datatables