Java Reference
In-Depth Information
}
function handleError() {
alert("A network error occurred. Please try again " +
"in a few moments.");
}
function handleResponse(response) {
if (response.available) {
alert(response.searchTerm + " is available!");
} else {
alert("We're sorry, but " + response.searchTerm +
" is not available.");
}
}
$("#usernameAvailability").on("click", checkUsername);
$("#emailAvailability").on("click", checkEmail);
</script>
</body>
</html>
Save this as ch16 _ question2.html .
The main source of duplication is the code that makes the actual request:
$.getJSON("ch14_formvalidator.php", parms).done(handleResponse);
Although it's a single line of code, it can be moved into a separate function to make it easier to
maintain. Plus, when you add a function for handling Ajax errors, you have to visit only one
function as opposed to two.
First write a function that displays a message to the user when the Ajax request fails. Call it
handleError() :
function handleError() {
alert("A network error occurred. Please try again " +
"in a few moments.");
}
Now write a function that performs the Ajax request, and chain a fail() call to done() :
function makeRequest(parameters) {
$.getJSON("ch14_formvalidator.php", parameters)
.done(handleResponse)
.fail(handleError);
}
You can now use this makeRequest() function inside the checkUsername() function:
Search WWH ::




Custom Search