Typeahead Implementation in PHP/MySQL

DEMO
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 = {};
    $('#person').typeahead({
        source: function (query, process) {
            $.ajax({
                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;
                        objects.push(object.full_name);
                    });
                    process(objects);
                }
            });
        }, //end source
        updater: function (item) {
            $('#first_name').val(map[item].fname);
            $('#middle_name').val(map[item].mname);
            $('#last_name').val(map[item].lname);
            return item;
        }
    }); //end of person typeahead
    $('#person').focus(function () {
        $(this).val('');
    });
});

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


header('Content-Type: application/json');
 require_once('connection.php');
 $i=0;
 $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))
 {
     $i++;
     $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

Hot/Cute flat-chested Girls