From http://www.w3schools.com (Copyright Refsnes Data)
| « Previous | Next Chapter » |
AJAX can be used to create more interactive applications.
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:
The form above has the following HTML code:
|
<form> First Name: <input type="text" id="txt1" onkeyup="showHint(this.value)" /> </form> <p>Suggestions: <span id="txtHint"></span></p> |
It is just a simple HTML form with an input field called "txt1".
An event attribute for the input 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.
The showHint() function is a very simple JavaScript function placed in the <head> section of the HTML page:
|
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.asp"; url=url+"?q="+str; url=url+"&sid="+Math.random(); xmlhttp.onreadystatechange=stateChanged; xmlhttp.open("GET",url,true); xmlhttp.send(null); } |
The function above executes every time a character is entered in the input field.
If there is input in the input field (str.length > 0), the showHint() function executes the following:
If the input field is empty, the function simply clears the content of the txtHint placeholder.
The showHint() function above calls a function named GetXmlHttpObject().
The purpose of the GetXmlHttpObject() function is to solve the problem of creating different XMLHTTP objects for different browsers:
|
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; } |
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.
| « Previous | Next Chapter » |
From http://www.w3schools.com (Copyright Refsnes Data)