26

I load my contact form into my page with JQuery/AJAX.

The contact form contains the reCaptcha scripts.

Unfortunately, JQuery removes the script tags before inserting them into my page. These script tags are needed because they output the captcha. now my loaded form has no captcha.

eSentrik
  • 520
  • 1
  • 5
  • 12

3 Answers3

23

@benck, great answer! But it's become a bit outdated. The current script URL is:

<script type="text/javascript" src="https://www.google.com/recaptcha/api.js"></script>

And the code should be like below:

grecaptcha.render('element_id', {
    sitekey: recaptchaSiteKey,
    callback: function(response) {
        console.log(response);
    }
});
drmonkeyninja
  • 8,490
  • 4
  • 31
  • 59
Oleg
  • 7,070
  • 4
  • 47
  • 49
21

The link has all you need: http://code.google.com/apis/recaptcha/docs/display.html

You can't add the script in ajax. You should add the following line before :

  <script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>

Then, you can dynamically create a recaptcha form in your js code by using adding the following code:

  Recaptcha.create("your_public_key",
    "element_id",
    {
      theme: "red",
      callback: Recaptcha.focus_response_field
    }
  );
Legionar
  • 7,472
  • 2
  • 41
  • 70
benck
  • 2,034
  • 1
  • 22
  • 31
  • I actually did this while waiting for a reply. came back to post my solution and find this. thanks anyways. nice to confirm my solution either way. – eSentrik Aug 31 '11 at 19:18
0

My approach is a bit different:

<script src='https://www.google.com/recaptcha/api.js?render=explicit' async defer></script>
<form>
    <input name="whatEver" type="text">
    <div id="captcha"></div>
    <button>submit</button>
</form>
<script>
var captchaWidgetId = grecaptcha.render( 'captcha', {
    'sitekey' : 'your_site_key'
    'theme' : 'light'
});
$(document).ready(function(){
    $('form').on('click','button', function(e){
        var formDatas = $(this).closest('form').serialize()+'&response='+grecaptcha.getResponse(captcha);
        $.post('post.php', formDatas, function(data){
            //successful
        });
    });
});
</script>
szmegma
  • 259
  • 4
  • 9