Wednesday, April 3, 2013

AJAX Auto Complete Feature Like Google, Facebook With PHP, MySQL

When i am working on one of my project, i need to work on AJAX. So i started googling about AJAX how to's. So i started learning AJAX slowly and steadily. After completion of learning AJAX i started working on AJAX Auto complete suggest feature. So i tried hard to work on that finally i got the solution from one of the online resource. I hope you are also one of the guy who is looking for such kind of solution. So i thought i should share this to my online users. One thing every one should get this in their mind that what actually an AJAX Auto complete is? Perhaps i too didn't have any idea but after working on that i came to know.

So let's see what an AJAX Auto complete suggest is? 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.


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.


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"



Step 3: Write AJAX Code

Write 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 cleaner 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 That's what an AJAX Autocomplete feature. Use this code snippet if your requirement matches. Do play with this code. Happy coding.

Did You Enjoy this Article ?

If yes, Then enter your email below to get

more such great articles in your inbox

For FREE !

25 comments:

  1. its showing error in ur Suggest.js At Line no. 55.
    i try To rectify bt Did't Get , U solve it and reply fast.

    ReplyDelete
    Replies
    1. Hey Apoorv kapil,

      Sorry for the delayed response...please replace the below code at line 54

      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;

      Now its gonna work...anyhow i have modified the code..please re-check once...thanks for your observation...

      Delete
  2. how can i get the searched value in textbox via aero(nevigation key)????

    ReplyDelete
  3. It does not work.

    ReplyDelete
    Replies
    1. Which part is not working can you please tell properly..

      Delete
  4. Replies
    1. Where do you get the error please tell me..its working fine for me...

      Delete
  5. i got error on line
    while($suggest = mysql_fetch_array($suggest_query))

    error : Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

    ReplyDelete
    Replies
    1. The code seems to be perfect..i don't know why you get this error...anyhow if you can send the complete code then i will let you know...

      Delete
  6. Code is working fine.

    If anyone having problem please check the copied code twice, some times junk spa n tag appears on line 2 in your copied code

    ReplyDelete
  7. Just set php error on, for proper debugging and customized development

    ReplyDelete
  8. sorry. where is the code for searchSuggest.php?!

    ReplyDelete
    Replies
    1. Hello Ali Masoumi, You can find out at Step 4.

      Delete
  9. error 404 pups below the searching text box:

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    body { color: #000000; background-color: #FFFFFF; }
    a:link { color: #0000CC; }
    p, address {margin-left: 3em;}
    span {font-size: smaller;}
    /*]]>*/-->
    Object not found!
    The requested URL was not found on this server.
    The link on the
    referring
    page seems to be wrong or outdated. Please inform the author of
    that page
    about the error.
    If you think this is a server error, please contact
    the webmaster.
    Error 404

    localhost
    Apache/2.4.4 (Unix) PHP/5.5.3 OpenSSL/1.0.1e mod_perl/2.0.8-dev Perl/v5.16.3

    ReplyDelete
    Replies
    1. Hey Ali, Its working perfectly for me. but why you are getting such kind of errors i dont know. Can you please give me the code where you are getting this error exactly.

      Delete
  10. Hey! I cannot change the style of the suggestbox. Can you give me a solution please? Thank you!

    ReplyDelete
    Replies
    1. Hey iPeere, you can add some class definition in the stylesheet and then add that class to the textbox. Check below code.
      Example:
      .textbox {
      border: 1px solid #848484;
      -webkit-border-radius: 30px;
      -moz-border-radius: 30px;
      border-radius: 30px;
      outline:0;
      height:25px;
      width: 275px;
      padding-left:10px;
      padding-right:10px;
      }

      Delete
  11. Hi! The code worked fine for me. Thanks and Congratulation. I would like to know how can I use this code to select the results with my up & down keys?

    ReplyDelete
  12. I want to use keyboard arrows to select specified item among the results returned like google and facebook How I do this?

    ReplyDelete
  13. Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\SocialUni\searchsuggest.php on line 15
    Call Stack
    #TimeMemoryFunctionLocation
    10.0008249336{main}( )..\searchsuggest.php:0
    21.0309257288mysql_fetch_array
    ( )..\searchsuggest.php:15

    ReplyDelete
  14. Hi Samiullah

    your auto-complete script, works perfect, now I need the auto-complete feature with the following adding to show a breadcrumb form a MySQL table parent_id based.



    Columns:

    Id

    Name

    Parent_id



    Waiting for your comments, regards from Mexico



    Francisco Cadena

    ReplyDelete
  15. can we have the source file of this?.

    ReplyDelete
    Replies
    1. mail me your email i will send you the source code.............

      Delete
  16. i want to change a text background color when i hover, how i do?

    ReplyDelete

Thank you for reading and commenting...