Ajax Bible
Note that the Google Suggest application discussed earlier indicates a new use of Ajax: you can now check every key as it’s typed. You might not want to do that everywhere in your application; checking every key can be quite a bottleneck, but you might need it in special cases, as when users enter a password or username and you want to tell that what they’re typing has already been used.
Take a look at an example in the downloadable code for this book: username.html and username.php. The username.html document asks users to enter the username they want, as you see in Figure 4.8.
If users take a username that’s already taken, such as nancy, the application informs them immediately that their username is not available, as you see in Figure 4.9.
The username.php script is easy enough; all it does is echo no if the username is nancy, and yes otherwise:
<?php if ($_GET["qu"] == "nancy"){ echo "no"; } else { echo "yes"; } ?>
How does username.html work? It just watches as the user types keystrokes, calling a function named checkUsername for each keystroke:
<body> <H1>Select a username</H1> Select your username <input id = "username" type = "text" name = "username" onkeyup = "checkUsername(event)"> <div id = "targetDiv"><div></div></div> </body>
In the checkUsername function, the user’s entered username is passed on to the username.php function as the parameter named qu:
function checkUsername(keyEvent) { var targetDiv = document.getElementById("targetDiv"); targetDiv.innerHTML = "<div></div>"; var input = document.getElementById("username"); if (input.value) { getData("username.php?qu=" + input.value); } }
All that’s left is to handle the value returned from username.php, yes or no, which is done in the getData function:
function getData(dataSource) { var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest(); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); } if(XMLHttpRequestObject) { XMLHttpRequestObject.open("GET", dataSource); XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { if(XMLHttpRequestObject.responseText == "no"){ var targetDiv = document.getElementById("targetDiv"); targetDiv.innerHTML = "<div>That username is not available.</div>"; } } } XMLHttpRequestObject.send(null); } }