reCAPTCHA v3 g-recaptch using form submit

698 Views Asked by At

I want to use recaptcha api but didn't want to rewrite this function. I have the key on the submit button and on the form tag. I can see its not generating the tokens just sending the sitekey. Any help would be great.

option one using the key in the form tag

<form method="POST" name="Form" id="Form" data-sitekey="Form hjkhjkhjkhjk">

option two using the key in the button tag

<button type="submit" 
    class=g-recaptch "btn btn-primary px-4 float-right" 
    data-sitekey="@reCaptchaKey">
   Submit
</button>

Goal is use this method for sending ajax request

$("#Form").submit(function(e) {
    e.stopPropagation();
    e.preventDefault();
    let formData = this.dataset.sitekey;
    console.log(formData);
    let submitter_btn = $(e.originalEvent.submitter);
    console.log(submitter_btn.data('sitekey'));
});

Working sample https://jsfiddle.net/tjmcdevitt/8cawy1kb/18/

1

There are 1 best solutions below

0
Kiran Shahi On BEST ANSWER

You have to use execute method of grecaptcha object. To do this, you need to add a render parameter to the reCAPTCHA script load. For details see the documentation.

$(document).ready(function() {
    $("#Form").submit(function(e) {
        e.stopPropagation();
        e.preventDefault();
         let formData = this.dataset.sitekey;
         let submitter_btn = $(e.originalEvent.submitter);
        
        grecaptcha.ready(function() {
            grecaptcha.execute(submitter_btn.data('sitekey'), {
                action: 'submit'
            }).then(function(token) {
                // Add your logic to submit to your backend server here.
                consle.log(token);
            });
        });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?render=6LeO3zwnAAAAAOlJQ4RePB73qug2OWQ1XjBWyYbV"></script>
<form method="POST" name="Form" id="Form" data-sitekey="Form hjkhjkhjkhjk">
  <label for="fname">First name:</label>
  <br>
  <input type="text" id="fname" name="fname" value="John">
  <br>
  <label for="lname">Last name:</label>
  <br>
  <input type="text" id="lname" name="lname" value="Doe">
  <br>
  <br>
  <input type="submit" value="Submit" data-sitekey="6LeO3zwnAAAAAOlJQ4RePB73qug2OWQ1XjBWyYbV">
</form>