Search code examples
javascriptruby-on-railsturbolinks

Javascript TypeError: variable is undefined


presently I am working on a Ruby on Rails app, and I am trying to get the below JS to work with the app. The first issue I came across was turbolinks 5.0 was preventing the page from loading the JS on initial load, and I would have to refresh the page in order to load the below JS. I did some googling, and came across this stackoverflow answer, but I can't seem to get the JS to run properly without throwing an error. Any and all help would be greatly appreciated.

orders.js

console.log('inside orders.js');

$(document).on('turbolinks:load', function() {
// Your JS here
var payment;

jQuery(function() {
  Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));
  return payment.setupForm();
});

payment = {
  setupForm: function() {
    return $('#new_order').submit(function() {
      $('input[type=submit]').attr('disabled', true);
      Stripe.card.createToken($('#new_order'), payment.handleStripeResponse);
      return false;
    });
  },
  handleStripeResponse: function(status, response) {
    if (status === 200) {

      // return alert(response.id);
      $('#new_order').append($('<input type="hidden" name="stripeToken" />').val(response.id));
      return $('#new_order')[0].submit();

    } else {

      // return alert(response.error.message);
      return $('#stripe_error').text(response.error.message).show();

    }
  }
};
});

Solution

  • As the comment mentioned above, the issue was related to where the jQuery statement was located in the JS. I restructured the JS to look like the following, and everything appears to be working now.

    orders.js

    console.log('inside orders.js');
    
    $(document).on('turbolinks:load', function() {
    // Your JS here
    var payment;
    
    payment = {
      setupForm: function() {
        return $('#new_order').submit(function() {
          $('input[type=submit]').attr('disabled', true);
          Stripe.card.createToken($('#new_order'), payment.handleStripeResponse);
          return false;
        });
      },
    
      handleStripeResponse: function(status, response) {
        if (status === 200) {
    
          // return alert(response.id);
          $('#new_order').append($('<input type="hidden" name="stripeToken" />').val(response.id));
          return $('#new_order')[0].submit();
    
        } else {
    
          // return alert(response.error.message);
          return $('#stripe_error').text(response.error.message).show();
    
        }
      }
    };
    
    jQuery(function() {
      Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));
      return payment.setupForm();
    });
    });