Creating Simple Auto-Complete Field with AJAX

Wednesday, June 18, 2008

I noticed the ajax auto-complete field for the first time when I type a keyword in google suggest, the field automagically giving me suggestion by displaying options to what word i might looked for beneath the text field, and now you can find this auto-complete variation very popular on search page. Here's a screenshot that I only typed "open" and google suggest me of what word may related to it and the amount of result accordingly. Here's a screenie.

What I will show you here is a simple quick way to do it. I will write a simple script that would auto-complete a word that user inputted with the stored words on database and returns the first match. Here's a complete list of the code

<head>
<script language="javascript">
function getXMLHttp() {
var XMLHttp = null;
if (window.XMLXMLHttpRequestuest) {
try {
XMLHttp = new XMLXMLHttpRequestuest();
}  catch (e) { }
}  else if (window.ActiveXObject) {
  try {
   XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
  XMLHttp = new ActiveXObject(
    "Microsoft.XMLHTTP");
  } catch (e) { }
 }
}
return XMLHttp;
}

function autocomplete (from, ev) {
   if (( ev.keyCode >= 48 && ev.keyCode <= 57 ) ||  ( ev.keyCode >= 65 && ev.keyCode <= 90 )) {        
var XMLHttpRequest = getXMLHttp();        
XMLHttpRequest.open
("GET", "suggest.php?word="+document.getElementsByName("txtWord")[0].value, true);               
XMLHttpRequest.onreadystatechange = function (  ) {            
if (XMLHttpRequest.readyState == 4) {                
var suggestion = XMLHttpRequest.responseText;                
var txtWord = document.getElementById ('txtWord');                 
if ((suggestion) && (txtWord.value == original_text)) {                    
//Gecko and Opera                    
if (document.getSelection) {                        
var initial_len = txtWord.value.length;                         
txtWord.value += suggestion;                         
txtWord.selectionStart = initial_len;                        
txtWord.selectionEnd = txtWord.value.length;                     }                    
//IE <= 6                    
else if (document.selection) {                        
var sel = document.selection.createRange (  );                        
sel.text = suggestion;                                   
sel.move ("character", -suggestion.length);                        
sel.findText (suggestion);                         sel.select (   );                    
}                
}
}        
}        
XMLHttpRequest.send (null);    
}
}
</script> </head> <body> <input style="position: absolute" type="text" name="txtWord" 
id="txtWord" onKeyup="autocomplete(this, event)" /> </body> 


At the server side, you have to create a php (or whatever server-side programming language) file that find the first match of text inputted by user and simply prints that value. The code in javascript will get that value via XMLHttpRequest.responseText and send it to input field. The remaining script in that javascript is meant to graft the end of the word we get from the responseText onto the beginning of the word, and select it.

The screenshot above shows that the code auto-completes my input from "au" to "automatic" and select the "tomatic" word. It's different presentation since google puts the options into a drop-down menu but I hope it gives a clue of how we get the completion words back.

Hope that helps.

0 comments: