Reputation: 1608
I've created a form that has remote: true
set on, and the create action responds to JS. Now when I added Stripe:
<script>
$(function() {
var $form = $('#payment-form');
$form.submit(function(event) {
// Disable the submit button to prevent repeated clicks:
$form.find('.submit').prop('disabled', true);
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
});
});
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Show the errors on the form:
$form.find('.card-payment-errors').text(response.error.message);
$form.find('.submit').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
// Insert the token ID into the form so it gets submitted to the server:
$form.append($('<input type="hidden" name="stripeToken">').val(token));
// Submit the form:
$form.get(0).submit();
}
};
</script>
even though my form has been set as remote, it submits it as an HTML. So I get redirected and the controller returns ActionController::UnknownFormat
because it doesn't know how to respond to HTML.
How can I make Stripe work the way it's supposed to, but have it not trigger the form as HTML. In console it also confirms: Processing by OrdersController#create as HTML
Upvotes: 1
Views: 184
Reputation: 17505
In the stripeResponseHandler
callback, you're submitting the form:
// Submit the form:
$form.get(0).submit();
This bypasses Rails' remote: true
mechanism. Since you want to send the token in an AJAX request, you need to do this explicitly in the handler, by calling $.ajax(...)
rather than $form.get(0).submit
.
I found this blog post that explains how to do exactly that!
Upvotes: 1