reCAPTCHA invisible without callback function

1.2k Views Asked by At

I have a form that's handled with an event listener and that doesn't play well with recaptcha's callback function.

Inside the form:

Form

<form class="myform>
...
<button class="g-recaptcha" data-sitekey="your_site_key" data-callback='onSubmit'>Submit</button>
</form>

Now it relies on function onSubmit to handle to get the token as below.

reCaptcha callback and token handler

var onSubmit = function(token) {
  console.log('token');
};

However I want to get the token in my form handler below. onSubmit and eventlistener below are fired at the same time but can't interchange the token.

My form handler where I want the token

$('form.myform').submit(function (event) {

    event.preventDefault();

    var form = $(this);
    var token = ''; // how do I get the token?
    submitForm(form, token); // token is not defined here but I want it to be

});
1

There are 1 best solutions below

0
On BEST ANSWER

You should trigger the form submit:

var onSubmit = function(token) {
    $( "form.myform" ).submit();
};

Your form submit handler function:

$('form.myform').submit(function (event) {

    event.preventDefault();

    var form = $(this);
    var token = grecaptcha.getResponse(); 
    submitForm(form, token);

});