Making the Ajax Call
When the user tries to submit the form, we need to make an Ajax call to a server-side routine to check the user's entered code against the string held in the session variable $string. We can add a JavaScript call to the form's submit button:
onclick="return checkform()"
We can then include our Ajax call as part of the standard form validation:
function checkform() {
// First the normal form validation
...
if(document.myform.code.value=='') {
alert('Please enter the string from the displayed image');
document.myform.code.value='';
document.myform.code.focus();
return false;
}
// Now the Ajax CAPTCHA validation
checkcode(document.myform.code.value);
return false;
}
The function checkcode() sets up the Ajax call:
function checkcode(thecode) {
http.open("GET", url + escape(thecode), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
The callback function handleHttpResponse() takes the value returned by the server-side routine, and either submits the form (if the codes match) or outputs an error message and returns the user to the form:
function handleHttpResponse() {
if (http.readyState == 4) {
captchaOK = http.responseText;
if(captchaOK != 1) {
alert('The entered code was not correct. Please try again');
document.myform.code.value='';
document.myform.code.focus();
return false;
}
document.myform.submit();
}
}
This site is brand new and so still somewhat under construction.
Why not bookmark it and call back regularly?