Search code examples
htmljqueryformsonsubmitrecaptcha-v3

jquery.submit function with event


We are writing a form with google recaptcha v3. The form needs to get the token before actually submitted. A colleague wrote this code and it works, the form submits without any problem. But I'm confused on why it would work? Why isn't it caught in an infinite loop when .submit() function is being called recursively?

jQuery.fn.extend({
  grecaptcha: function (options) {
    this.submit(function (e) {
      e.preventDefault();
      var key = options["recaptcha_site_key"];
      var acdata = options["action_data"];
      var ele = this;
      grecaptcha.execute(key, { action: acdata }).then(function (token) {
        $("<input>")
          .attr({
            type: "hidden",
            name: "g-recaptcha-response",
            value: token,
          }).appendTo($(ele));
        ele.submit();
      });
    });
  },
});
$("#formID").grecaptcha(option);

Are there any other better approaches to request a token before submitting?


Solution

  • Per : https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit

    This method is similar, but not identical to, activating a form's submit . When invoking this method directly, however:

    No submit event is raised. In particular, the form's onsubmit event handler is not run.

    Your code sample is not calling the jQuery method to trigger a submit event on the form. That would, in fact, result in a loop. Try wrapping the ele variable jQuery. $(ele).submit () should result in a loop. By not wrapping the reference to this (e.currentTarget) in a jQuery object, and instead calling the DOM submit function, you are submitting the form without triggering an event or running the handler.

    Makes sense?