Ginger Squirrel
Ginger Squirrel

Reputation: 663

How do I pass a parameter to this Google ReCaptcha function?

I am having an issue getting the count parameter to pass into the verifyCallback in the following piece of code:

var CaptchaCallback = function () {
  console.log('CaptchaCallback run');
  var count = 0;

  $('.g-recaptcha').each(function (index, el) {
    grecaptcha.render(el, { 
      'sitekey': 'xxx', 
      'callback': verifyCallback(count) 
    });
    count++;
  });
};

If I remove the parameter everything works as it should, only the parameter can't be passed for an essential part of the function.

If I add the parameter the function runs straight away without waiting for the ReCaptcha to be verified.

I want to be able to pass the parameter and then have the function run when the ReCaptcha is verified.

Here is the function that the parameter is passed to if it helps:

function verifyCallback(formNumber) {
  //var formNumber = 1;
  console.log('verifyCallback');
  $('#submitBtn_' + formNumber).prop('disabled', false);
  console.log('#submitBtn_' + formNumber);
}

Edit: When I use the parameter it doesn't bring the count through, it brings back the response from Google...

Thank-you

Upvotes: 1

Views: 3277

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337627

The issue is because you're calling the verifyCallback function immediately and assigning the returned value of that function to the callback property.

To fix this, wrap the function call in an anonymous function which is then provided as a reference to the callback. Also note that you can use the index value from the each() handler instead of manually maintaining the count variable. Using this method will also mean that you don't need to use a closure to keep the count value in scope of the current iteration. Try this:

var CaptchaCallback = function () {
  console.log('CaptchaCallback run');

  $('.g-recaptcha').each(function (index, el) {
    grecaptcha.render(el, { 
      sitekey: 'xxx', 
      callback: function() {
        verifyCallback(index) 
      });
    });
    count++;
  });
};

Upvotes: 5

Related Questions