AJAX ExampleIn 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 web form. Type a Name in the Box Below NOTE CLICK HERE TO SEE WORK---this won't work here because of Cross-Domain origin restrictionSuggestions: PHP CODEExample Explained - The HTML FormThe form above has the following HTML code:
As you can see 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 the user inputs data, a function called "showHint()" is executed. The execution of the function is triggered by the "onkeyup" event. In other words: Each time the user moves his finger away from a keyboard key inside the input field, the function showHint is called. Example Explained - The showHint() FunctionThe showHint() function is a very simple JavaScript function placed in the <head> section of the HTML page. The function contains the following code:
The 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:
If the input field is empty, the function simply clears the content of the txtHint placeholder. Example Explained - The stateChanged() FunctionThe stateChanged() function contains the following code:
The stateChanged() 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.
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:
<?php //'Fill up array with names //'get the q parameter from URL //'lookup all hints from array if length of q>0 //'Output "no suggestion" if no hint were found |