Membuat Fitur AJAX Auto Complete seperti di Google, Facebook menggunakan PHP, MySQL

Tulisan diambil dari http://www.phphunger.com

Ketika saya sedang bekerja, saya memerlukan bantuan Ajax. Lalu saya mulai googling tentang  AJAX, bagaimana cara menggukannya, dll. Saya mulai belajar  AJAX secara pelan-pelan dan terus-menerus. Setelah cukup belajar AJAX saya mulai bekerja pada fitur AJAX Auto complete. Jadi saya berusaha keras untuk bekerja yang pada akhirnya saya mendapat solusi dari salah satu sumber online. Saya harap Anda juga salah satu orang yang sedang mencari seperti saya. Jadi saya pikir saya harus berbagi kepada pengguna online saya.  Mungkin saya juga tidak punya ide tapi setelah bekerja akhirnya saya  mengetahui caranya.
Sekarang marilah kita pelajari apa itu  AJAX Auto complete? As a web developer almost all us in our daily life, use Google at its best. When we start googling like “how to” or “AJAX tutorial” etc then the Google will show some results beneath its search text box. See below picture for better understanding. So this feature is called as AJAX Auto complete Suggest Feature. Now a days all of the websites have this feature.
ajax-autocomplete-fetaure
Now Let’s see how to design such an application.
Step 1: Design the Database. 
 
See the below picture for better understanding of database design. In this tutorial, i have just created one table for demonstration purpose. The process is same for the bigger database also. In this tutorial i assumed the database name as “phphunger_ajax_autocomplete” and table name as “games”. Change the names as your wish.
ajax-autocomplete-db
Create the table as “games”
CREATE TABLE IF NOT EXISTS `games` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;
Dump some data into the table “games”
INSERT INTO `games` (`id`, `name`) VALUES
(1, 'Angry Birds'),
(2, 'Angry Birds Space'),
(3, 'Angry Birds Space Battle'),
(4, 'Babe Rescue'),
(5, 'Ball Defence'),
(6, 'Ball Defence  2');
Once the database design phase is over the next step is to design the front end for the user from where he starts searching the content.
Step 2: Design the HTML Form
Here add one Textbox on the HTML Form which communicates with AJAX and fetches data from the back-end to the front-end. See below picture how the form looks like. Name the file as “index.html”
ajax-autocomplete-phphunger
<!DOCTYPE HTML>
<html>
<head>
  <script language="JavaScript" type="text/javascript" src="suggest.js"></script>
  <title>AJAX Autocomplete With PHP - phphunger.com</title>
</head>
<body>
Simple AJAX Search Suggest:
<form id="suggestSearch">
<input type="text" id="dbTxt" alt="Search Criteria" onKeyUp="searchSuggest();" autocomplete="off"/>
<div id="layer1"></div>
</form>
</body>
</html>
Step 3: Write AJAX CodeWrite some javascript code which includes the AJAX Request, Response logic. See below code. Name the file as “suggest.js”suggest.js

function getXmlHttpRequestObject() {
 if (window.XMLHttpRequest) {
  return new XMLHttpRequest();
 } else if(window.ActiveXObject) {
  return new ActiveXObject("Microsoft.XMLHTTP");
 } else {
  alert("Your Browser Sucks!");
 }
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
 if (searchReq.readyState == 4 || searchReq.readyState == 0) {
  var str = escape(document.getElementById('dbTxt').value);
  searchReq.open("GET", 'searchSuggest.php?search=' + str, true);
  searchReq.onreadystatechange = handleSearchSuggest;
  searchReq.send(null);
 }
}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
 if (searchReq.readyState == 4) {
         var ss = document.getElementById('layer1');
  var str1 = document.getElementById('dbTxt');
  var curLeft=0;
  if (str1.offsetParent){
      while (str1.offsetParent){
   curLeft += str1.offsetLeft;
   str1 = str1.offsetParent;
      }
  }
  var str2 = document.getElementById('dbTxt');
  var curTop=20;
  if (str2.offsetParent){
      while (str2.offsetParent){
   curTop += str2.offsetTop;
   str2 = str2.offsetParent;
      }
  }
  var str =searchReq.responseText.split("\n");
  if(str.length==1)
      document.getElementById('layer1').style.visibility = "hidden";
  else
      ss.setAttribute('style','position:absolute;top:'+curTop+';left:'+curLeft+';width:250;z-index:1;padding:5px;border: 1px solid #000000; overflow:auto; height:105; background-color:#F5F5FF;');
  ss.innerHTML = '';
  for(i=0; i < str.length - 1; i++) {
   //Build our element string.  This is <span class="IL_AD" id="IL_AD5">cleaner</span> using the DOM, but
   //IE doesn't support dynamically added attributes.
   var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
            suggest += 'onmouseout="javascript:suggestOut(this);" ';
            suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
            suggest += 'class="small">' + str[i] + '</div>';
            ss.innerHTML += suggest;
  }
 }
}
//Mouse over function
function suggestOver(div_value) {
 div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
 div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
 document.getElementById('dbTxt').value = value;
 document.getElementById('layer1').innerHTML = '';
 document.getElementById('layer1').style.visibility = "hidden";
}
Step 4: Connect to Database and Fetch Results. This is the file for database connection and fetching results from table. Name it as searchSuggest.php
<!doctype html>
<html>
<head>
<title>AJAX Autocomplete With PHP - phphunger.com</title>
</head>
<body>
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("phphunger_ajax_autocomplete") or die(mysql_error());
if (isset($_GET['search']) && $_GET['search'] != '') {
 //Add slashes to any quotes to avoid SQL problems.
 $search = $_GET['search'];
 $suggest_query = mysql_query("SELECT distinct(name) as autosuggest FROM games WHERE name like('" .$search . "%') ORDER BY name");
 while($suggest = mysql_fetch_array($suggest_query)) {
  echo $suggest['autosuggest'] . "\n";
 }
}
?>
</body>
</html>
That’s what an AJAX Autocomplete feature. Use this code snippet if your requirement matches. Do play with this code. Happy coding.
Tulisan diambil dari http://www.phphunger.com
This entry was posted in Pemrograman PHP. Bookmark the permalink.

One Response to Membuat Fitur AJAX Auto Complete seperti di Google, Facebook menggunakan PHP, MySQL

  1. ahmad syarifudin says:

    keren

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s