When a user types a character in the input field above, the function "showHint()" is executed. The function is triggered by the "onkeyup" event:
Start typing a name in the input field below: Suggestions: |
Source code explanation:
If the input field is empty (str.length==0), the function clears the content of the txtHint placeholder and exits the function.
If the input field is not empty, the showHint() function executes the following:
- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send the request off to a file on the server
- Notice that a parameter (q) is added to the URL (with the content of the input field)
The PHP File
The page on the server called by the JavaScript above is a PHP file called "gethint.php".
The source code in "gethint.php" checks an array of names, and returns the corresponding name(s) to the browser:
0
if (strlen($q) > 0) { $hint=""; for($i=0; $i |
Explanation: If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:
- Find a name matching the characters sent from the JavaScript
- If no match were found, set the response string to "no suggestion"
- If one or more matching names were found, set the response string to all these names
- The response is sent to the "txtHint" placeholder
No comments:
Post a Comment