Home  >  Q&A  >  body text

reCAPTCHA v3 g-recaptch uses form submission

I want to use recaptcha api but don't want to rewrite this function. My keys are on the submit button and form label. I can see that it doesn't generate the token, just sends the site key. Any help would be great.

Option 1 uses keys in form tags

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

Option two uses the key in the button label

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

The goal is to send an ajax request using this method

$("#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 example https://jsfiddle.net/tjmcdevitt/8cawy1kb/18/

P粉877719694P粉877719694277 days ago437

reply all(1)I'll reply

  • P粉395056196

    P粉3950561962024-01-17 13:57:23

    You must use the execute method of the grecaptcha object. To do this, you need to add rendering parameters to the reCAPTCHA script load. See Documentation for details.

    $(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>

    reply
    0
  • Cancelreply