steven_noble
steven_noble

Reputation: 4203

Why isn't my form communicating with Stripe?

On the page that contains my order form, in the <head>, I have:

= jquery_include_tag Rails.application.config.jquery_version
= javascript_include_tag "https://js.stripe.com/v2/"
:javascript
  $(function(){
    Stripe.setPublishableKey('pk_test_NEgBLhQ1dJGvlE8SDFEXqRQ4');
  });
  (function() {
    var stripeResponseHandler;

    $("#new_order").submit(function(event) {
      var form;
      form = $(this);
      form.find("#submit_order").prop("disabled", true);
      Stripe.createToken(form, stripeResponseHandler);
      return false;
    });

    stripeResponseHandler = function(status, response) {
      var form, token;
      form = $("#new_order");
      if (response.error) {
        form.find(".payment-errors").text(response.error.message);
        form.find("#submit_order").prop("disabled", false);
      } else {
        token = response.id;
        form.append($("<input type=\"hidden\" name=\"stripeToken\">").val(token));
        form.get(0).submit();
      }
    };

  }).call(this);

The key you see listed above is labelled "Test Publishable Key" at https://manage.stripe.com/account/apikeys.

The form on that page includes:

= simple_form_for @order, :html => {:id => "new_order"} do |f|
  = f.error_notification
  = text_field_tag :number, nil, :name => nil, "data-stripe" => "number"
  = text_field_tag :cvc, nil, :name => nil, "data-stripe" => "cvc"
  = text_field_tag :expiry_month, nil, "data-stripe" => "exp-month"
  = text_field_tag :expiry_year, "data-stripe" => "exp-year"
  = f.button :submit, :as => :button, :id => 'submit_order'  

(With all the labels/placeholders/etc and non-Stripe fields stripped out.)

At present I am running this in development mode on localhost without any SSL.

When I complete an order with valid or invalid credit card data and click Create Order, my Rails app logs an order but the Javascript does not seem to communicate with the Stripe server. I see no errors -- or any Javascript activity at all as far as I can tell -- in Chrome's Javascript console. And I see no charges -- successful or otherwise -- at https://manage.stripe.com/test/events.

I know my way around Rails but am a Javascript novice. How can I diagnose what's going on here? And what might be the cause?

Upvotes: 1

Views: 113

Answers (1)

Asherah
Asherah

Reputation: 19347

  (function() {

This should maybe be

  $(function() {

(and you can ditch the .call(this) stuff)

It's executing immediately in the <head>, which probably means $("#new_order") isn't finding the form — the browser hasn't even rendered it, or possibly even received the HTML for it off the network, yet — so the selector matches zero items, and the event binding is a no-op.

Alternatively, if you put the code just before your </body>, that'd do the trick, too.

(Also, putting the Stripe.setPublishableKey() in a $(function() { … }) block is not useful.)

Upvotes: 1

Related Questions