AJAX Suggest: The JavaScript File
This page includes a link to a JavaScript page
<script src="ShowHint.js"></script>
which contains a function
showHint
as below.
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.
- A parameter (
q
) with the content of the input field is added to the URL.
function showHint( str ) {
if ( str.length == 0 ) {
document.GetElementById("txtHint").innerHTML = "";
return;
}
if ( window.XMLHttpRequest ) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest( );
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function( ) {
if ( ( xmlhttp.readyState == 4 ) &&
( xmlhttp.status == 200 ) ) {
document.GetElementById("txtHint").innerHTML =
xmlhttp.responseText;
}
}
xmlhttp.open( "GET", "GetHint.php?q="+str, true );
xmlhttp.send( );
}
|