Thread: Ajax
View Single Post
  #11  
Old 05-04-2009, 06:08 PM
welcomewiki welcomewiki is online now
Member
 
Join Date: Dec 2008
Location: India
Posts: 80,537
The JavaScript

The JavaScript code is stored in "clienthint.js" and linked to the HTML document:




var xmlHttp;

function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="gethint.php";
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 || xmlHttp.readyState=="complete")
{
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;
}


Example Explained

The showHint() Function
This function executes every time a character is entered in the input field.
If there is some input in the text field (str.length > 0) the function executes the following:
  1. Defines the url (filename) to send to the server
  2. Adds a parameter (q) to the url with the content of the input field
  3. Adds a random number to prevent the server from using a cached file
  4. Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object to execute a function called stateChanged when a change is triggered
  5. Opens the XMLHTTP object with the given url.
  6. Sends an HTTP request to the server
If the input field is empty, the function simply clears the content of the txtHint placeholder.




The stateChanged() Function
This function executes every time the state of the XMLHTTP object changes.


When the state changes to 4 (or to "complete"), the content of the txtHint placeholder is filled with the response text.





The GetXmlHttpObject() Function
AJAX applications can only run in web browsers with complete XML support.


The code above called a function called GetXmlHttpObject().
The purpose of the function is to solve the problem of creating different XMLHTTP objects for different browsers.
This is explained in the previous chapter.
Reply With Quote