Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Submit with Braintree Custom Form

I have a Braintree custom form located inside a Bootstrap modal. Right now, the Braintree form works fine if I place a submit button inside the form. When I click that submit button, Braintree intercepts it and runs it submission handler that gets the nonce and then returns it to the onPaymentMethodReceived method. So far, so good. But, I would like to use a nice, Bootstrap themed button at the bottom of the modal to submit the form rather than a submit button within the <form> tag itself.

However, if I setup such a button and give it a click action of $( "#paymentForm" ).submit();, that seems to submit it in a traditional fashion rather than firing Braintree's handler. Is there any way to trigger Braintree's submission handler programmatically?

like image 863
Timothy R. Butler Avatar asked Mar 07 '26 02:03

Timothy R. Butler


1 Answers

One thing you can do is provide a button in the form itself, but have it hidden. And have the button in the bootstrap footer click the real button. This will allow the Braintree's form submit hijacking to work correctly.

<form id="form" method="post" action="/checkout">
  <div id="payment-form"></div>
  <input type="submit" style="position:fixed; top:-200%;left:-200%;" id="real-btn">
</form>
<button type="submit" id="fake-btn">Pay</button>

<script type="text/javascript" src="https://js.braintreegateway.com/js/braintree-2.27.0.min.js"></script>
<script type="text/javascript">
  var clientToken = "YOUR_TOKEN_HERE";
  var fakeBtn = document.getElementById('fake-btn');
  var realBtn = document.getElementById('real-btn');

  braintree.setup(clientToken, 'dropin', {
    container: 'payment-form'
  });

  fakeBtn.addEventListener('click', function (e) {
    realBtn.click();
  });
</script>

In addition, here's a codepen using jQuery and Bootstrap to accomplish the solution in a Bootstrap modal.

The demo uses this Bootstrap modal example and the pre-generated client token from the Braintree docs. It uses the onPaymentMethodReceived callback to illustrate that the tokenization was a success, but is not necessary for the solution if you just want to submit the form.

like image 95
BladeBarringer Avatar answered Mar 10 '26 09:03

BladeBarringer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!