#ReCaptcha #Invisible #beta with #Ajax #Jquery
The Google Recaptcha invisible beta isn’t really invisible… you get a logo down in the bottom left hand corner, and it prompts you to select “images of sushi” (or similar), which is more annoying than “I am not a robot”.
I’ve opted to use Ajax and jQuery with it, for more control, so lets see how that’s done – I’ve omitted my keys and the server side code is C# asp.net
Include the script in the head;
then add this div anywhere on the page
And then on the call to action (i.e. search) call:
grecaptcha.execute();
but don’t perform the ajax post yet, wait for recaptcha_callback to be called. Then in the recaptcha_callback, call your back-end script, passing the captcha reponse
var strUrl = “/ajax.aspx”;
$.post(strUrl, {
captcha: grecaptcha.getResponse()
}, function (data) {
// Display your data here
});
On the server side, you need to validate the captcha data as follows;
var captcha = Request.Form[“captcha”];
var webClient = new WebClient();
const string strSecretKey = “YOUR PRIVATE KEY”;
var strUrl = string.Format(“https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}”, strSecretKey, captcha);
string verification = webClient.DownloadString(strUrl);
var jsSerializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
var isOK = jsSerializer.Deserialize<CaptchaObject>(verification).success;
if (isOK)
{
// go look up your data
Response.Write(strJson);
}
Where CaptchaObject is defined as follows
public class CaptchaObject
{
public bool success { get; set; }
public string challenge_ts { get; set; }
public string hostname { get; set; }
}