The following AJAX example will demonstrate how a web page can communicate with a web server while a user enters data into an HTML form.
Type a name in the input field below:
Suggestions:
Example explained - The HTML page
The HTML page contains a link to an external JavaScript, a simple HTML form, and a span element:
<> <> < type="text/javascript" src="clienthint.js">< /script > < /head > <>
<> First Name: < type="text" id="txt1" onkeyup="showHint(this.value)"> < /form > <>Suggestions: < id="txtHint">< /span >< /p >
< /body > < /html > |
The HTML form above has an input field called "txt1". An event attribute for this field defines a function to be triggered by the onkeyup event.
The paragraph below the form contains a span called "txtHint". The span is used as a placeholder for data retrieved from the web server.
When a user inputs data, the function called "showHint()" is executed. The execution of the function is triggered by the "onkeyup" event. In other words: Each time a user moves the finger away from a keyboard key inside the input field, the function showHint is called.
Example explained - The JavaScript code
This is the JavaScript code, stored in the file "clienthint.js":
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 XMLHTTP!"); 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) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } }
function GetXmlHttpObject() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari return new XMLHttpRequest(); } if (window.ActiveXObject) { // code for IE6, IE5 return new ActiveXObject("Microsoft.XMLHTTP"); } return null; } |