Maciek Semik Maciek Semik - 4 months ago 69
Ajax Question

braintree payments wont work with ajax submit

I have a dynamic AJAX submit. I am trying to submit braintree (paypal) payment data into payment.php using AJAX. Unfortunately, braintree is giving me a nonce error. braintree creates an input with a code (nonce) on submit, but my submit is submitted before the code is created.

Braintree gives me a script that creates the code

<script src="https://js.braintreegateway.com/v2/braintree.js"></script>


And I use something like

$(document).on("submit","form",function(event){
if(!$(this).is("[action]")){
event.preventDefault()
formdata=new FormData(this)
submit(this)
}


submit(this) calls the ajax. I tried to delay the submit, but then nothing works. For example. If I call an alert() during my submit, the code is added and the submit works fine; except for the fact that now I have an alert. The problem is that both codes run at the same time and the braintree code is too slow to react. I also tried to re-position the link above and below my JS code with no luck. Any ideas or suggestions thanks.

Answer

As mentioned here, I think you should use onPaymentMethodReceived callback from GlobalSetup of BrainTree. Instead of handling form submit on your own using jQuery, you can configure this callback in the setup like below.

    braintree.setup("CLIENT-TOKEN-FROM-SERVER", "dropin", {
      container: "dropin-container",
      onPaymentMethodReceived: function (paymentMethod) {
        // Do some logic in here.
        // When you're ready to submit the form:
        myForm.submit();
      }
   });

The onPaymentMethodReceived is called when a payment_method_nonce has been generated by Drop-in (as the result of a form submission). It will be called with a paymentMethod object, which contains the nonce as a string.

You can find more details here about the paymentMethod object passed to onPaymentMethodReceived callback, it has a property called nonce.

Hope this helps :)