Using Google's ReCaptcha within an Ajax Context
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!
POPULAR TOPICS
TOPICS
- Agriculture
- Architecture
- Art
- Associations
- Automobiles
- Beauty
- Building and Construction
- Business Services
- Computers and Internet
- Education
- Embassies
- Engineering
- Entertainment
- Environment
- Fashion
- Financial and Legal
- Government
- Health
- Hospitality
- Housing and Real Estate
- Imports and Exports
- Industrial
- NGOs
- Religious Bodies
- Security
- Shopping Centres
- Social Services
- Society and Culture
- Sports and Leisure
- Transportation
- Travel and Tourism
- Utilities