I'm using stripe with rails and the ajax calls seem to work fine whenever I refresh the page. I believe this is an issue with turbolinks, the 'ready page:load' doesn't work as I expected.
Here's the form for the card:
<%= form_tag subscribers_path, id:'subscriber_form' do %>
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add Card</h4>
</div>
<div class="modal-body">
<div class="field">
<%= label_tag :"Card Number" %>
<%= text_field_tag nil, nil, "data-stripe":"number", size:"20" %>
</div>
<div class="field">
<%= label_tag :"Expiration Date" %>
<%= text_field_tag nil, nil, "data-stripe":"exp_month", size:"2" %>/
<%= text_field_tag nil, nil, "data-stripe":"exp_year", size:"2" %>
</div>
<div class="field">
<%= label_tag :"CVC" %>
<%= text_field_tag nil, nil, "data-stripe":"cvc", size:"4" %>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<%= submit_tag "Add card", class:"btn btn-primary submit", id:"card_submit_button" %>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
<% end %>
And the Javascript:
$(document).on('ready page:load', function () {
$('#subscriber_form').submit(function(event) {
var $form = $(this);
console.log($form);
$form.find('.submit').prop('disabled', true);
$form.find('.submit').val('loading...');
Stripe.card.createToken($form, stripeResponseHandler);
return false;
});
var stripeResponseHandler = function(status, response) {
var $form = $('#subscriber_form');
if (response.error) {
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
$form.find('.submit').val('submit');
} else {
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
var dataSet = $form.serialize();
$.ajax({
type: "POST",
url: $form.attr("action"),
data: dataSet,
dataType: "script",
complete: function(){
$form.get(0).reset();
console.log(response);
$('#card_select input:last').prop("checked", "checked");
$('#cardModal').modal('hide')
$form.find('.submit').prop('disabled', false);
$form.find('.submit').val('Add card');
},
error: function(exception){console.log("exception" + exception);}
});
}
};
});
The script still doesn't work when I follow a link to the page.
As far as I know there is no .on('ready') so maybe you should try an approach similar to this:
var stripe;
stripe = function() {...};
$(document).ready(stripe);
$(document).on('page:load', stripe);