js problem with onsubmit event when trying to enable recaptcha verification

57 views Asked by At

i am trying to add recaptcha verification to my web site so i did that, but i added a code to add the verification to all my web site forms, now, my problem is how to verify the captcha if not succeded it must stop the event and show alert message and if succeded let the form to complete i can do that by using form.submit()) but the problem if any form has other onsubmit method that works to verify or submit the form in an other logic etc, when using form.submit()) it can submit the form even if the original handler stopped that, i want to solve the problem please

$(document).ready(function () {
  const recaptchaScript = document.createElement("script");
  recaptchaScript.src = "https://www.google.com/recaptcha/api.js?render=site_key";
  recaptchaScript.async = true;
  recaptchaScript.defer = true;
  document.head.appendChild(recaptchaScript);


  let success = false;
let event_obj = "";
  function verifyReCAPTCHAAndSubmit(form) {


    grecaptcha.ready(function () {
      grecaptcha.execute("site_key", { action: "submit" }).then(function (token) {
        if (!token) {
          alert("The reCAPTCHA token is missing or invalid. Please try again.");
          success = false;

          return false;
        }

        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/services/recaptcha.php', true);
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              const response = JSON.parse(xhr.responseText);
              if (response.success && response.score >= 0.3) {
                // reCAPTCHA verification succeeded
                success = true;
                continueFormSubmission(form);
              } else {
                alert("reCAPTCHA verification failed. Please try again.");
                success = false;

              }
            } else {
              alert("An error occurred while verifying reCAPTCHA. Please try again.");
              success = false;

            }
          }
        };
        xhr.send('response=' + token);
      });
    });
  }

  function continueFormSubmission(form) {
    // Directly invoke the form's submit method to ensure it's the last step
event_obj.returnValue = true;
alert("jj");
return true;
  }

  $('form').on('submit', function (event) {
    const form = event.target;
event_obj = event;
    verifyReCAPTCHAAndSubmit(form);
    event.preventDefault();

  });
});

0

There are 0 answers