Thursday, April 15, 2010

Implement reCAPTCHA with Classic ASP and Validate with AJAX

A friend asked me to help implementing reCAPTCHA with classic ASP which I successfully managed to implement even though I have not dabbled much with ASP - read the implementation here.
So now the expectations rise and he asks me to validate reCaptcha using AJAX - I do not have any experience of AJAX combined with ASP either.

Going through the resources section of the recaptcha.net site did not help much in this regard. So here are the steps that I did to achieve this. Note that most parts of the solution here have been taken from various pages on the net which are listed at the bottom of this post in the References section.


There are 6 parts of the code as follows:
  1. JavaScript to create reCaptcha on the page that has the input form
  2. Insert the created reCaptcha in the desired location
  3. Generic JavaScript to make AJAX call
  4. Make AJAX call to Server-side component to validate reCaptcha
  5. Handle AJAX validation response from server-side component
  6. Server side component to validate the reCaptcha

1. JavaScript to create reCaptcha on the page that has the input form
Here is the code that needs to be placed in the ASP file to generate the JavaScript which when called, generates the code for reCaptcha. The generated string needs to be placed in your form where you want the reCaptcha to be displayed.

<%
recaptcha_public_key = "XXXXXXXXXXXXXXXX"
function recaptcha_challenge_writer(publickey) 
  recaptcha_challenge_writer = "<script type=""text/javascript"">" & _ 
 "var RecaptchaOptions = {" & _ 
 " theme : 'red'," & _ 
 " tabindex : 0" & _ 
 "};" & _ 
 "</script>" & _ 
 "<script type=""text/javascript"" src=""http://api.recaptcha.net/challenge?k=" & publickey & """></script>" & _ 
 "<noscript>" & _ 
 "<iframe src=""http://api.recaptcha.net/noscript?k=" & publickey & """ frameborder=""1""></iframe>
 " & _ 
 "<textarea name=""recaptcha_challenge_field"" id=""recaptcha_challenge_field"" rows=""3"" cols=""40""></textarea>" & _ 
 "<input type=""hidden"" name=""recaptcha_response_field"" id=""recaptcha_response_field"" value=""manual_challenge"">" & _ 
 "</noscript>" 
end function 
%>

2. Insert the created reCaptcha in the desired location
Here is how you need to place the code in your form where you want the reCaptcha to be displayed.

<%=recaptcha_challenge_writer(recaptcha_public_key)%>

3. Generic JavaScript to make AJAX call
Here is a generic JavaScript function to make an AJAX call


4. Make AJAX call to Server-side component to validate reCaptcha
Here is the JavaScript "onClick" function that will make the specific call to the server-side component to validate the reCaptcha input.



5. Handle AJAX validation response from server-side component
Here code that needs to be put in the asp file that processes the submitted form.

// The function for handling the response from the server
var showMessageResponse = function (oXML) { 
    
    // get the response text, into a variable
 var response = oXML.responseText;
    
    // act on the result from the server
 if (response == "PASS") {
  //alert("Captcha Passed ...");
  document.getElementById("Form1").action = "process_form.asp";
  document.getElementById("Form1").submit();
 }  else {
        // Reload the captcha image if the validation failed & alert the user
 alert("Captcha Failed. Please try again ...");
 Recaptcha.reload();
 }
};

6. Server side component to validate the reCaptcha
Here code that needs to be put in the asp file that processes the submitted form.

'Define some variables to be used on page
dim pubkey, privkey, challenge, form_response, test_captcha, recaptcha_confirm

'Customize your public and private keys and other variables
pubkey = "XXXXXXXXXXXXXXXX"
privkey = "XXXXXXXXXXXXXXXX"

' Get the user input
challenge = Request.Form("recaptcha_challenge_field")
form_response = Request.Form("recaptcha_response_field")

' Generate the POST string for reCaptcha
Dim VarString
VarString = _
"privatekey=" & privkey & _
"&remoteip=" & Request.ServerVariables("REMOTE_ADDR") & _
"&challenge=" & challenge & _
"&response=" & form_response

' Make an AJAX call to validate input reCaptcha
Dim objXmlHttp
Set objXmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
if isNull(objXmlHttp) then
Set objXmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
end if
objXmlHttp.open "POST", "http://api-verify.recaptcha.net/verify", False
objXmlHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXmlHttp.send VarString

' Receive response from reCaptcha server
Dim ResponseString
ResponseString = split(objXmlHttp.responseText, vblf)
Set objXmlHttp = Nothing

if ResponseString(0) = "true" then
'They answered captcha correctly
    response.write("PASS")
else
'They answered captcha incorrectly
    response.write("FAIL")
end if


Note:
  1. Of course, you need to sign-up for a free reCaptcha account at reCaptcha.net.
  2. The above steps 1, 3, 4 & 5 can be put in the same script block.
  3. The above step 2 needs to be put in the place in the form where reCaptcha is to be shown.
  4. Remember to substitute the public & private keys with the ones that you get when you sign up for a free reCaptcha account.
  5. This is a very basic, no-frills version. You can modularize, clean-up, optimize and add more error-handling. But this should be good enough to get you started!

References:
  1. This Google Groups post
  2. reCaptcha resources page
  3. This post on Jeff Niblack's Blog
  4. This post on World of Code Blog
  5. This blog post on Dark Side of Carton.

5 comments:

Anonymous said...

Isn't the internet great? Thanks to it, everyone share codes and experiences.

I spent over 12 hours trying to figure out the instructions from RECAPCHA and GOOGLE (both one?) and could not make heads and tails on how to implement it via ajax.

I'd tried, at least, 1,000 possible combinations on how to load on the HTML and on the AJAX side.

It just would not verify.

Finally, I ended up here and, with some studying of the code, I was able to make a super clean implementation.

Thank you very much for posting your experience.

Darshan Shah said...

Glad to be able to help - I had faced the same problem so when I resolved it, I put it up here to help out others.
Keep checking the blog for more such posts!

Anonymous said...

So where is the code for steps 2 and 3? I can handle the step 2 part on my own from other resources, step 3 however is missing, and its kind of important.

Darshan Shah said...

Thanks for pointing this out. I had upgraded Syntax Highlighter but missed out a few critical things, hence the code was showing up. It should show up now.

Anonymous said...

i am a newbie...Can you pls post example. i am confused where to put what

LinkWithin

Related Posts Plugin for WordPress, Blogger...