Passing variables in invisible reCaptcha callback

I am creating a website form in our CMS application that uses the new invisible Google reCaptcha.

However, I'm fixated on how to use the reCaptcha callback?

Before using captcha, the code was very simple:

HTML

<form> Form input fields here... <button id="a23k4l234lj2l-submit-button"></button> </form> 

JQuery

 $('#a23k4l234lj2l-submit-button').click(function (e) { e.preventDefault(); var that = $(this); if(Abayo.validate(that)) { Abayo.submit(that); } }) 

The Abayo library has functions for validating specific forms and submitting data to a script that processes form data.

Now I want to add reCaptcha to the form. The documentation states the following:

1 Create a div with data size = 'invisible'.

 <div class="g-recaptcha" data-sitekey="your_site_key" data-callback="onSubmit" data-size="invisible"> </div> 

2 Call grecaptcha.execute from the javascript method.

 grecaptcha.execute(); 

This works, but the captcha callback function ONLY gives me a response code to check for user response confirmation:

G-recaptcha-response user response will be entered for your callback function.

The answer only tells me if I can send my request to the server.

Do I need the location of the submit button, the DOM element, or ANY kind of button identification to extract data from the form that CONNECTs the button?

Using the following code, I can’t get the data from the form and send it to the server?

 $('#a23k4l234lj2l-submit-button').click(function (e) { e.preventDefault(); grecaptcha.execute(); }) var onSubmit = function(response) { // var that cannot be defined, I don't have a DOM element anywhere? var that = ???? if(Abayo.validate(that)) { Abayo.submit(that); } } 

Question

Is there a way to get the DOM element in a reCaptcha callback?

+5
source share
2 answers

You can programmatically create your recaptcha.

First create your captcha div.

 <div id="myCaptcha" /> 

Then visualize captcha and pass your data with a token.

 var that = $(this); grecaptcha.render('myCaptcha', { sitekey: 'xxx', callback: function(token) { Abayo.submit(token, that) } }); 

Read more here https://developers.google.com/recaptcha/docs/invisible#js_api

+5
source

Have you tried dynamically setting the onSubmit function (keeping the div tag as it is with data-callback="onSubmit" ):

 $('#a23k4l234lj2l-submit-button').click(function (e) { e.preventDefault(); var that = $(this); if(Abayo.validate(that)) { window.onSubmit = function(){ // defining onSubmit function dynamically here Abayo.submit(that); // you can access `that` here }; grecaptcha.execute(); } }) 

Note. I do not have a site key to verify this code. Therefore, consider this as an approach, not a working sample code.

+1
source

Source: https://habr.com/ru/post/1265179/


All Articles