Ajax javascript code for Autocomplete, textbox hint.


The showHint Function takes in a string on the Onkeyup event (which means the user has started to type something, and with each keystroke, the event is fired which processes the javascript function)

The html :

<form name="frmSearch" id="frmSearch" action="Search.asp" method="get" class="searchIE">
        <input name="txtSearch" id="txtSearch" type="text" onkeyup="showHint(this.value)" />
        <div id="txtHint"></div>
</form>

The showHint function gets the textbox input by using innerHTMl of the id of the textbox. This.Value refers to the textboxe's value which is sent to the function. The function makes an http Object via calling the method highlited in orange in the script (this is like a buffer for html to be written to or like opening an invisible page the user can't see). The script opens the URL, highlited in orange where it is defined, and it uses a get request (gets a variable from the invisible page's QueryString let's say) What this means is that we can send a variable to a defined page via Javascript that is behind the scenes, then the page we defined can echo(PHP) or Respnse(.NET) or write html. This html is then used to modify the innerHTMl of the div below the textbox (process highlited in blue) all with one Javascript function.

The Javascript:

var xmlHttp

function showHint(str)
{
if (str.length==0)
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  }
var url="gethint.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

Last update:
2014-08-20 05:11
Author:
Mark
Revision:
1.2
Average rating:0 (0 Votes)

You cannot comment on this entry

Chuck Norris has counted to infinity. Twice.