reCaptcha inside a with jQuery ajax() or load() dynamically loaded object

For the German version of this article, please look here.

The Problem: you want to use reCaptcha with the JS (JavaScript) or php-Api in in a with jQuery ajax() or load() dynamically loaded area. But: the reCaptcha doesn’t appear.

My use case looked something like this:

contakt.html (abridged):

<div id="form"></div>
<script>$("#form").load("mail.php?ajax");</script>

mail.php (abridged): 

<?php
// here is other code
echo '<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script><div id="recaptcha"></div>';
echo '<script>Recaptcha.create("my_public_key", "recaptcha", {theme: "red"});</script>';
// other code
?>

And this, like I said, doesn’t work.

The problem:
google’s reCaptcha API uses the document.write() function for inserting reCaptcha in to the document tree. This function is not available in this case, when the content is loaded dynamically with jQuery. document.write() therefore has to be replaced with its jQuery equivalent.

This means you either have to maintain your own version of the api or you work this out dynamically. Our solution looked something like this:

mail.php (abridged): 

echo '<script type="text/javascript" src="jsapi.php"></script><div id="recaptcha"></div>';

jsapi.php (complete):

<?php
$api = file_get_contents('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js');
$api = str_replace('document.write','$("body").append',$api);
echo $api;
?>

The replacing could be made manually and is highly trivial. Therefore I did not attach a changed version of the recaptcha_ajax.js. You probably need to do something about the header to make the api cacheable for the browser again, but this was not our focus.

Kommentar verfassen