In the AJAX example below we will demonstrate how a web page can communicate with a web server online as a user enters data into a standard HTML form.
Example Explained - The HTML Form
<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
Example Explained - The showHint() Function
The showHint() function is a very simple JavaScript function placed in the <head> section of the HTML page.
The function contains the following code:
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="http://www.allhimachal.com/ajaxhint.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
Example Explained - The GetXmlHttpObject() Function
The example above calls a function called GetXmlHttpObject().
The purpose of the function is to solve the problem of creating different XMLHTTP objects for different browsers.
The function is listed below:
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 stateChanged() Function
The stateChanged() function contains the following code:
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
The stateChanged() function executes every time the state of the XMLHTTP object changes.
When the state changes to 4 ("complete"), the content of the txtHint placeholder is filled with the response text.
Enjoy Code.