Validating Credit Card Data With Stripe Error - javascript

In Rails, I'm working on integrating Stripe into a project I'm working on. As it is a membership site, I need to collect cc data when a user makes an account. I've already installed the stripe gem and added the keys.
I have the following fields on devise/registrations/new.html.erb
<div class="form-group">
<div class="row">
<div class="col-md-8">
<%= label_tag :card_number, "Credit Card Number" %>
<%= text_field_tag :card_number, nil, {:name => nil, :'data-stripe' => "number", class: "form-control"} %>
</div>
<div class="col-md-4">
<%= label_tag :card_code, "CVC" %>
<%= text_field_tag :card_code, nil, {:name => nil, :'data-stripe' => "cvc", class: "form-control"} %>
</div>
</div>
</div>
<div class="form-group">
<%= label_tag nil, "Expiration Date" %>
<div class="row">
<div class="col-md-3">
<%= select_month nil, { use_two_digit_numbers: true }, {:name => nil, :'data-stripe' => "exp-month", class: "form-control"} %>
</div>
<div class="col-md-3">
<%= select_year nil, { start_year: Date.today.year, end_year: Date.today.year+10 }, {:name => nil, :'data-stripe' => "exp-year", class: "form-control"} %>
</div>
</div>
</div>
Next, I need to validate these fields on submission of the form. I was directed to do this with javascript, so I created a new file registrations.js.coffee:
jQuery ->
Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
payment.setupForm()
payment =
setupForm: ->
$('#new_registration').submit ->
$('input[type=submit]').attr('disabled', true)
Stripe.card.createToken($('#new_registration'), payment.handleStripeResponse)
false
handleStripeResponse: (status, response) ->
if status == 200
alert(response.id)
else
alert(response.error.message)
When I submit this form on localhost, I get the error message: SyntaxError: [stdin]:14:5: unexpected if
(in c:/Users/Bill/Desktop/testapp/app/assets/javascripts/registrations.js.coffee)
This line of code is highlighted:
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
Actual indent of coffee:

Related

Dynamically update rails form textarea based on dropdown select

I have a table called Email_Template. It contains two columns: template_name and template_body.
I also have a form in which user selects template_name in dropdown (coming from database column). In the same form, based on template_name selection, the textarea should display corresponding “template_body” content coming from the same database table. Please tell me how to do this.
My Form
<%= form_for :email_form, :html => {:class => "form-horizontal"}, url: candidates_send_email_path do |f| %>
<div class="form-group">
<%= f.label :template_name, "Template" %>
<div class="col-md-10">
<%= select_tag "template_name", options_from_collection_for_select(Email_Template.all, "id", "id") %>
</div>
</div>
<div class="form-group">
<%= f.label :template_body, "Template Body" %>
<div class="col-md-10">
<%= f.text_area :email_content, rows: 7 %><br/>
</div>
</div>
<div class=text-right>
<%= f.button class: "btn btn-primary btn-modal" do %>
SEND EMAIL <i class="glyphicon glyphicon-send"></i>
<% end %>
</div>
<% end %>
routes.rb
post '/template_body_finder/:template_id' => 'search#find_template'
search_controller.rb
def find_template
#email_template = Email_Template.find(params[:template_id])
respond_to do |format|
format.js
end
end
search.js.coffee
$ ->
$(document).on 'change', '#template_id', (evt) ->
template_id = $(this).val()
window.alert(template_id)
curr_url = "/template_body_finder/" + template_id
$.ajax({
type: 'POST',
url: curr_url,
data: {'template_id': template_id},
success: ( data, status, xhr ) -> })
find_template.js.erb
$(“#email_content”).val= <%= #email_template.template_body %>
;
Here try this:-
1- your form
<%= form_for :email_form, :html => {:class => "form-horizontal"}, url: candidates_send_email_path_path do |f| %>
<div class="form-group">
<%= f.label :template_name, "Template" %>
<div class="col-md-10">
<%= select_tag "template_name", options_from_collection_for_select(Email_Template.all, "id", "id") %>
</div>
</div>
<div class="form-group">
<%= f.label :template_body, "Template Body" %>
<div class="col-md-10">
<%= f.text_area :email_content, rows: 7 %><br/>
</div>
</div>
<div class=text-right>
<%= f.button class: "btn btn-primary btn-modal" do %>
SEND EMAIL <i class="glyphicon glyphicon-send"></i>
<% end %>
</div>
<% end %>
<script type="text/javascript">
$('#template_name').on('change', function(){
var template_id = $(this).val();
// alert(template_id);
// ajax request
$.ajax({
url: "/template_body_finder",
type: "GET",
data : {
template_id: template_id
},
dataType: "script",
});
})
</script>
2- change your url:
get '/template_body_finder' => 'search#find_template'
3- in controller -
def find_template
#email_template = Email_Template.find(params[:template_id])
respond_to do |format|
format.js
end
end
4- in your find_template.js.erb file it should like this-
$('#email_form_email_content').val("<%=#email_template.template_body%>");
this works for me, if you have any doubt you can ask in comments.
thank you.

Form won't submit with AJAX

app/assets/javascripts/profiles.js
This is my javascript for the form. The jQuery hide/show are working but the AJAX request is not..
$(document).on('page:load ready', function() {
$('#pair-search').hide();
$('#date-search').hide();
$('input[type="radio"]').click(function() {
if ($(this).attr("value") == "pair") {
$("#pair-search").show();
$("#date-search").hide();
}
else {
$("#date-search").show();
$("#pair-search").hide();
}
$('#search-form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType:'script',
data: $(this).serialize(),
success: function(data) {
if (data) {
$('#profiles').html(data);
}
}
});
});
});
});
And here is the form on my profiles(#index) page ...it renders two partials. I will post the partial for "pair-search" so you can get an idea of how the forms work together.
app/assets/views/profiles/index.html.erb
User Search
<div id = "first_option">
<%= form_tag users_path, method: :get, id: 'search-form' do %>
<label>Who are you looking for?</label><br>
<input type="radio" id=pairchoice name="choice" value="pair"> Paired <br>
<input type="radio" id=datechoice name="choice" value="date"> Date <br>
<% end %>
</div>
<div class = "choices">
<div id = "pair-search">
<%= render 'pair_search' %>
</div>
<div id = "date-search">
<%= render 'date_search' %>
</div>
</div>
<div id = "profiles">
</div>
Pair search partial:
app/assets/views/profiles/_pair_search
<%= form_tag(profiles_path, method: :get, :id =>'search-form') do %>
<%= label(:language, 'What are your preferred languages?') %><br>
<%= check_box_tag('search[language]', 'Ruby') %>
<%= label_tag('search[language]', 'Ruby') %>
<%= check_box_tag('search[language]', 'JavaScript') %>
<%= label_tag('search[language]','JavaScript') %>
<%= check_box_tag('search[language]', 'Python') %>
<%= label_tag('search[language]', 'Python') %>
<%= check_box_tag('search[language]', 'Java') %>
<%= label_tag('search[language]','Java') %>
<%= check_box_tag('search[language]', 'PHP') %>
<%= label_tag('search[language]','PHP') %>
<%= check_box_tag('search[language]', 'C++') %>
<%= label_tag('search[language]','C++') %><br>
<%=label_tag(:operating_system,"What is your Operating System of choice?") %><br>
<%= check_box_tag('search[operating_system]', 'Unix') %>
<%= label_tag('search[operating_system]','Unix') %>
<%= check_box_tag('search[operating_system]', 'Linux') %>
<%= label_tag('search[operating_system]','Linux') %><br>
<%= label_tag(:age, 'What age-range are you looking for?')%><br>
<%= check_box_tag('search[age]', '20-25') %>
<%= label_tag('search[age]','20-25') %>
<%= check_box_tag('search[age]', '25-30') %>
<%= label_tag('search[age]', '25-30') %>
<%= check_box_tag('search[age]', '30-35') %>
<%= label_tag('search[age]', '30-35') %>
<%= check_box_tag('search[age]', '40-45') %>
<%= label_tag('search[age]','40-45') %><br>
<%= check_box_tag('search[age]', '50+') %>
<%= label_tag('search[age]','50+') %>
<%= label_tag(:gender, "Gender:") %>
<%= check_box_tag('search[male]') %>
<%= label_tag('search[male]', 'Male' )%>
<%= check_box_tag('search[female]')%>
<%= label_tag('search[female]', 'Female')%>
<%= check_box_tag('search[other]') %>
<%= label_tag('search[other]', 'Other')%>
<%= label_tag(:location, "Where do you want the person you're searching for to live?") %>
<%= text_field_tag ('search[location]') %>
<%= submit_tag("Search", :id => "search") %>
<% end %>

Issue with Payment method selection when I add Braintree Drop-in UI in Spree Store

I'm trying to implement extension to accommodate drop-in UI of braintree when customer selects Braintree as a payment method. If I add braintree js code into _gateway.html.erb then all the other payment methods stop working. If I select any other method except braintree and click "Save and continue" then nothing happens. "Save and continue" button just gets disabled.
I've overwritten spree/frontend/app/views/spree/checkout/_gateway.html.erb.
<% if payment_method.name == "Braintree" %>
<div id="dropin"></div>
<% else %>
<div class="well clearfix">
<%= image_tag 'credit_cards/credit_card.gif', :id => 'credit-card-image', :class => 'pull-right', :width => '170', :height => '28' %>
<% param_prefix = "payment_source[#{payment_method.id}]" %>
<p class="field">
<%= label_tag "name_on_card_#{payment_method.id}" do %>
<%= Spree.t(:name_on_card) %><abbr class="required" title="required">*</abbr>
<% end %>
<%= text_field_tag "#{param_prefix}[name]", "#{#order.billing_firstname} #{#order.billing_lastname}", { id: "name_on_card_#{payment_method.id}", :class => 'form-control required'} %>
</p>
<p class="field" data-hook="card_number">
<%= label_tag "card_number" do %>
<%= Spree.t(:card_number) %><abbr class="required" title="required">*</abbr>
<% end %>
<% options_hash = Rails.env.production? ? {:autocomplete => 'off'} : {} %>
<%= text_field_tag "#{param_prefix}[number]", '', options_hash.merge(:id => 'card_number', :class => 'form-control required cardNumber', :size => 19, :maxlength => 19, :autocomplete => "off") %>
<span id="card_type" style="display:none;">
( <span id="looks_like" ><%= Spree.t(:card_type_is) %> <span id="type"></span></span>
<span id="unrecognized"><%= Spree.t(:unrecognized_card_type) %></span>
)
</span>
</p>
<div class="row">
<div class="col-md-8 field" data-hook="card_expiration">
<%= label_tag "card_expiry" do %>
<%= Spree.t(:expiration) %><abbr class="required" title="required">*</abbr>
<% end %>
<%= text_field_tag "#{param_prefix}[expiry]", '', :id => 'card_expiry', :class => "form-control required cardExpiry", :placeholder => "MM / YY" %>
</div>
<div class="col-md-4 field" data-hook="card_code">
<%= label_tag "card_code" do %>
<%= Spree.t(:card_code) %><abbr class="required" title="required">*</abbr>
<% end %>
<%= text_field_tag "#{param_prefix}[verification_value]", '', options_hash.merge(:id => 'card_code', :class => 'form-control required cardCode', :size => 5) %>
<%= link_to "(#{Spree.t(:what_is_this)})", spree.content_path('cvv'), :target => '_blank', "data-hook" => "cvv_link", :id => "cvv_link" %>
</div>
</div>
<%= hidden_field_tag "#{param_prefix}[cc_type]", '', :id => "cc_type", :class => 'ccType' %>
</div>
<% end %>
<%= #client_token = Braintree::ClientToken.generate %>
<script type="text/javascript">
braintree.setup("<%=#client_token%>", 'dropin', {
container: 'dropin'
});
</script>
I work at Braintree. If you don't specify the form option inside the call to braintree.setup, braintree.js will attach its behavior to the closest parent form element. Since it looks like the parent form of your braintree container is the same form used by the other checkout flows, braintree.js will indeed hijack the call made by the submit button (regardless of the payment flow being used). I recommend creating two separate form elements, and passing the id of the one used by braintree to the braintree.setup call.
braintree.setup("<%=#client_token%>", 'dropin', {
container: ‘dropin’,
form: ‘braintree_checkout'
});

"First argument in form cannot contain nil or be empty" bug

Hello guys i would like someone to help me fix this bug.....i would like to sign up an account but i fail whenever i click register and i get the error above...Anyone who can help me fix this
please help me out i have tried and i can not understand why..
Below is my code for all the controllers responsible
code for the registrations controller
class RegistrationsController < Devise::RegistrationsController
#include Wicked::Wizard
#before_filter :configure_permitted_parameters, if: :devise_controller?
def new
super
end
def create
super
end
protected
def after_inactive_sign_up_path_for(resource)
user_steps_path
end
end
below is the code for the user_steps controller
class UserStepsController < ApplicationController
include Wicked::Wizard
steps :finishing_step
def show
#user = User.last
render_wizard
end
def update
render_wizard
end
private
def finish_wizard_path
current_user.update_attributes(complete: true)
redirect_to root_path
end
end
below is my code for the applications controller
class ApplicationController < ActionController::Base
layout :layout_by_resource
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, :alert => exception.message
end
before_filter do
resource = controller_name.singularize.to_sym
method = "#{resource}_params"
params[resource] &&= send(method) if respond_to?(method, true)
end
def after_sign_in_path_for(resource)
#this is where i decide that before user fills all fields he/she should be redirected to the user_steps_path
if resource.complete?
root_path
else
user_steps_path
end
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:first_name, :last_name, :phone_number,
:city, :nationality, :address_first_line, :address_second_line, :date_of_birth,
:email, :password, :password_confirmation, :terms_of_service )}
end
protected
def layout_by_resource
if devise_controller?
"login"
else
"application"
end
end
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :email, :password) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:name, :email, :password, :current_password, :is_female, :date_of_birth, :avatar) }
end
end
below is my code for the form that i want to submit to the user account after confirmation from the personal email
<%= form_for #user, url: wizard_path do |f| %>
<div><%= f.label :first_name, "First Name" %><br />
<%= f.text_field :first_name %></div>
<div><%= f.label :middle_name, "Middle Name" %><br />
<%= f.text_field :middle_name %></div>
<div><%= f.label :last_name, "Last Name" %><br />
<%= f.text_field :last_name %></div>
<div><%= f.label :phone_number, "Phone Number" %><br />
<%= f.text_field :phone_number %></div>
<div><%= f.label :date_of_birth, "Date of Birth" %><br />
<%= f.date_select :date_of_birth, start_year: 1900 %></div>
<div><%= f.label :address_first_line, "Address (first line)" %><br />
<%= f.text_field :address_first_line %></div>
<div><%= f.label :address_second_line, "Address (second line)" %><br />
<%= f.text_field :address_second_line %></div>
<div><%= f.label :city, "City" %><br />
<%= f.text_field :city %></div>
<div><%= f.label :nationality, "Nationality" %><br />
<%= country_select(:user, :nationality, {selected: "UG"}) %></div>
<div>
<%= f.label :avatar %>
<%= f.file_field :avatar %>
</div>
<div>
<%= f.label :terms_of_service, "Agree to Terms of Service" %> <br>
<%= f.check_box :terms_of_service %>
</div>
<div><%= f.submit "Register" %></div>
<% end %>
For any help thanks in advance.....

Issues customizing Stripe payment form

Apologies in advance for the long question. I am new to Rails and Stacked Overflow and am running into road blocks.
I have stripe payments working in my app through my payments controller. The localhost:3000/payments/new works perfectly, but now I need to expand it in my app reservation app.
Currently when a user finds a table they like at a venue they can make a reservation. I did this by copying over the reservation/new form into a partial in my tables show page for a specific table
tables/show:
<%= render :partial=>'new_reservation', :locals=> {:reservation => Reservation.new(:table_id=> #table.id)} %>
And the following code for the partial:
<%= form_for(reservation) do |f| %>
<% if reservation.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(reservation.errors.count, "error") %> prohibited this reservation from being saved:</h2>
<ul>
<% reservation.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :user_id %><br>
<%= f.number_field :user_id %>
</div>
<div class="field">
<%= f.label :table_id %><br>
<%= f.number_field :table_id %>
</div>
<div class="field">
<%= f.label :reservation_date %><br>
<%= f.date_field :reservation_date %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Now I'd like to add the following code from my payments/new file to this partial to integrate stripe into the new reservation process:
<div id="new_card">
<div class="field">
<%= f.hidden_field :stripe_token %>
</div>
<div class="field">
<label>Card Number</label>
<input id="card-number" type="text" placeholder="4242 4242 4242 4242" />
</div>
<div class="field">
<label>CV Code</label>
<input id="cvc" type="text" placeholder="123" />
</div>
<div class="field">
<label>Expiry Month</label>
<input id="exp-month" type="text" placeholder="12" />
</div>
<div class="field">
<label>Expiry Year</label>
<input id="exp-year" type="text" placeholder="14" />
</div>
</div>
<div class="field">
<%= f.label :amount %><br />
<%= f.text_field :amount %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I have updated the javascript for my reservation.js to the following:
$( function() {
$('#card-number').reservation'formatCardNumber')
$('#cvc').reservation('formatCardCVC')
$('#exp-month, #exp-year').reservation('restrictNumeric')
$(document).on('click', "#new_reservation [name='commit']", function( event ) {
if( $('input[name=saved_card]:checked').val() !== 'true' ) {
event.preventDefault()
var card = {
number: $("#card-number").val(),
expMonth: $("#exp-month").val(),
expYear: $("#exp-year").val(),
cvc: $("#cvc").val()
}
Stripe.createToken(card, function( status, response ) {
if (status === 200) {
$("[name='reservation[stripe_token]']").val(response.id)
$("#new_reservation").submit()
} else {
$("#stripe-error-message").text(response.error.message)
$("#credit-card-errors").show()
$("#user_submit").attr("disabled", false)
}
} )
}
} )
$("[name='saved_card']").change( function() {
showSaved = $(this).val() === 'true'
$('#saved_card').toggle( showSaved )
$('#new_card').toggle( ! showSaved )
} )
$("[name='saved_card']").eq(0).prop( 'checked', true ).change()
} )
The only issue is these payment do not show up on my stripe dashboard nor does the stripe_token pass to reservations.stripe_token through the hidden field.However, I get no errors and the reservation shows up as complete.
I have loaded the proper js in my application header, and stripe works when I use payments/new. Not sure why when i copy over the code it fails.
Should I attack the problem at another angle?

Categories

Resources