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>

mail.php (abridged): 

// here is other code
echo '<script type="text/javascript" src=""></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):

$api = file_get_contents('');
$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.

[ad name=“Google Adsense-1 small horizontal“]

Ein Gedanke zu „reCaptcha inside a with jQuery ajax() or load() dynamically loaded object

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

This site uses Akismet to reduce spam. Learn how your comment data is processed.