|
Tweaking reCaptcha to work with AJAX
Yesterday, I was working on a website that required a "Contact Us" form. I wanted to add a CAPTCHA to the form so the recipient's inbox wouldn't be flooded with spam emails. I have used CAPTCHAs in the past, but I decided to use a new (more "sophisticated") CATPCHA. It's freely avaiable at http://www.recaptcha.net.
I wanted to submit the form with an AJAX call (you know, one of those features that everybody wants to see these days). It would do one of two things: 1) If successful, it would say something like "Thanks for the message!" or 2) "We're sorry, but your message wasn't deliverable." The latter message would popup when the user did not fill in the CAPTCHA correctly.
However, I did not find an easy way to do this. I tried reading their API page to no avail. (Frankly, I didn't spend a whole lot of time that page or on its demo page.)
Problem
I wrote some code that displayed the error message and it worked just fine. However, it did not refresh the CAPTCHA. Why is this a problem you may ask? Well, for security purposes, reCatpcha only allows the one try per capture. If the user doesn't answer it correctly, a new CAPTCHA must be displayed.
Solution
I think I have found something that works. In the callback (and after the HTTP request has sent back '200'), I check the result to see if it contains a snippet of my error message (the word "CAPTCHA"). If it does, I know that the user did not enter the CAPTCHA correctly. I then make a call to a built-in function: Recaptcha.reload(). This will reload the code required to produce a CAPTCHA, thereby giving the user a new CAPTCHA to solve.
Download
Available for download is a zipped file.
Additional Notes
I have not written any error checking into this example, so you'll notice that the form doesn't complain when the user leaves the CAPTCHA blank (i.e., you won't see the error message). That said, the form only sends email when the CAPTCHA is properly filled out.
Please note that you will have to enter your own public/private reCaptcha keys (index.php and sendMail.php) as well as modify the "To" field in sendMail.php.
Feedback
I would appreciate any feedback regarding my solution. You may post a comment on my blog: blog.mladineo.com.
Cheers, Fernando
|