WallyJ
1 month ago
1286
10
JavaScript

Javascript Form Submit to URL or Controller

Posted 1 month ago by WallyJ

Newb Question of the day. I have some Javascript on a page to handle Braintree payments which stops the normal submittal of the form to perform some functions, using:

event.preventDefault();

I'm assuming that the form is actually submitted at the end of the function:

form.submit(function(event) {
      console.log("Function - Submit Form");
      event.preventDefault();

      var formIsInvalid = false;
      var state = hostedFieldsInstance.getState();

      // perform validations on the non-Hosted Fields
      // inputs
      if (!validateEmail() || !validateInput($('#cc-name'))) {
        formIsInvalid = true;
      }

      // Loop through the Hosted Fields and check
      // for validity, apply the is-invalid class
      // to the field container if invalid
      Object.keys(state.fields).forEach(function(field) {
        if (!state.fields[field].isValid) {
          $(state.fields[field].container).addClass('is-invalid');
          formIsInvalid = true;
        }
      });

      if (formIsInvalid) {
        // skip tokenization request if any fields are invalid
        return;
      }
      console.log("Function - Hosted Fields - Tokenize");
      hostedFieldsInstance.tokenize({
        // include the cardholderName in the tokenization
        // request
        cardholderName: $('#cc-name').val()
      }, function(err, payload) {
        if (err) {
          console.log("There was a Payload Error");
          console.error(err);
          return;
        }

        // This is where you would submit payload.nonce to your server
        $('#payment-method-nonce').val(payload.nonce);
        console.log("Declared the Nonce");
        console.log("End of Function");
      });
    });
  });
});
</script>

but other examples I've seen have an additional "form.submit()" at the end of the function.

I added that but the form submits over and over, thousands of times (Seen on the Network Tab in Chrome Dev Tools)

The beginning of my form looks like this:

<form class="needs-validation" novalidate="" method="POST" action="/payment/subscribe">
{{csrf_field()}}

But when I click button on the form I see all of my console.log statements, but it doesn't submit to the URL, which goes to a controller.

Why is that?

Please sign in or create an account to participate in this conversation.