Search code examples
jquerytwitter-bootstrapbraintree

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?


Solution

  • 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.