Welcome, or Sign up

Forgot your password?

Using Google's ReCaptcha within an Ajax Context

POSTED IN Computers and Internet  WRITTEN BY: kabudu
Comments 0 COMMENTS

For the past 2 days I faced a rather unusual and annoying issue. I was trying to integrate Google's Recaptcha (yes, it seems Google has bought them over) into a simple registration form with stages loaded in via Ajax.

Everytime I got to the stage that included the captcha, then the overlay containing the form would disappear and the entire parent page would go blank; not the nicest of expected outcomes.

In the end I traced this to the fact that Google uses "document.write" to place dynamically generated Javascript from the API endpoint into your webpage in order to display the Captcha, and it turns out that when the document has already fully loaded "document.write" replaces the entire contents of your webpage with the respective content it is serving! Surely Google, there must be better ways of injecting Javascript into the DOM!

The solution I utilised in the end (rather hacky but hey, gets the job done) was the following:

$captcha = file_get_contents({Recaptcha API endpoint URL});

$captcha = str_replace('document.write','$("body").append',$captcha);

So essentially I replaced the document.write with a jQuery equivalent for injecting content into the DOM, in this case Javascript, before evaluating the Javascript.

I hope this helps you and saves you hours of nail-biting, hair-pulling agony!

 



 

Add your comment

© 2012 Portaltoafrica.com. All rights reserved