Issues customizing Stripe payment form - javascript

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?

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.

How to store course other than dropdown menu and open new textbox put other educations?

Model field - degree, institute, percentage these are the model field.
If course is other than dropdown menu so select "Other" and display textbox for enter user education. and when form submit i want to store education in degree column. but now i am not able to handle these two value.
education.html.erb file
<p>
<%= f.label :user_id, "Select User.*" %>
<% if params[:user_id] != nil %>
<%= f.select :user_id, :collection => User.where(:id => params[:user_id]).map{|u| ["#{u.firstname}, #{u.lastname}", u.id]} %>
<% else %>
<% #selected_user_id = EducationInformations.where(:id => params[:id]).pluck(:user_id).first %>
<%= f.select :user_id, :collection => User.where(:id => #selected_user_id).map{|u| ["#{u.firstname}, #{u.lastname}", u.id]} %>
<% end %>
</p>
<br/>
<% course = ["MCA","BCA","BSC","Engg","Diploma in computer science","Other"] %>
<p>
<%= f.label :degree, "Select Course.*" %>
<%= f.select :degree , :collection => (course) %>
</p>
<div id="other_edu">
<br/>
<p>
<%= f.label :other_degree, "Enter your course" %>
<%= f.text_field :other_degree , :id => "other_course", :onblur => "getCourse()" %>
</p>
</div>
<br/>
<p>
<%= f.label :institute, "Institute*" %>
<%= f.text_field :institute %>
</p>
<br/>
<p>
<%= f.label :percentage, "Grade/Percentage" %>
<%= f.text_field :percentage %>
</p>
javascript
$(document).ready(function() {
var select = document.getElementById('education_informations_degree');
var other_course = document.getElementById('other_course');
$('#other_edu').hide();
select.onchange = function() {
var selected_course = select.value;
if (selected_course == "Other")
{
$('#other_edu').show();
}else{
$('#other_edu').hide();
}
}
});
function getCourse() {
var x = document.getElementById("other_course");
var select = document.getElementById('education_informations_degree');
select.value = x.value;
console.log(x.value);
}
Model
class EducationInformations < ActiveRecord::Base
unloadable
attr_accessible :user_id, :degree, :institute, :passing_year, :country, :university, :percentage
validates :degree, presence: true
validates :passing_year, presence: true
validates :university, presence: true
validates :institute, presence: true
end
Controller
def create
#edu_info = EducationInformations.new(educational_params)
if #edu_info.save
#flash[:notice] = 'Vote saved.'
redirect_to #edu_info
else
render "new"
end
end
private
def educational_params
params.require(:education_informations).permit(:user_id, :degree, :institute, :passing_year, :country, :university, :percentage)
end
How I fixed this problem when user select value from dropdown list so I set value as textbox value. If I select "Other" item so display textbox and whatever user can enter so I send value of text. I know this is not best way but I think this solution handle my problem.
View code
<% course = ["MCA","BCA","BSC","Engg","Diploma in computer science","Other"] %>
<p>
<%= label_tag "select_degree", "Select Course *" %>
<%= select_tag "select_degree" , options_for_select(course) %>
</p>
<div id="other_edu">
<br/>
<p>
<%= f.label :degree, "Enter your course *" %>
<%= f.text_field :degree %>
</p>
</div>
<br/>
<p>
<%= f.label :institute, "Institute *" %>
<%= f.text_field :institute %>
</p>
<br/>
<p>
<%= f.label :percentage, "Grade/Percentage " %>
<%= f.text_field :percentage %>
</p>
Javascript
$(document).ready(function() {
var select = document.getElementById('select_degree');
var other_course = document.getElementById('education_informations_degree');
$('#other_edu').hide();
select.onchange = function() {
var selected_course = select.value;
if (selected_course == "Other")
{
$('#other_edu').show();
}else{
$('#other_edu').hide();
other_course.value = select.value;
}
}
});

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'
});

Validating Credit Card Data With Stripe Error

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:

form not displayed in page source

i am creating a veiw page in my rails application
this is my view page :
<html>
<head>
<%= stylesheet_link_tag "$.multiselect2side", :media => "all" %>
<%= javascript_include_tag "$.multiselect2side" %>
<script>
$().ready(function() {
$("#student_name_id").multiselect2side();
});
</script>
<script>
function callGrade(grade_value_123) {
var id = grade_value_123;
}
</script>>
</head>
<body>
<div class="container">
<h1> <%= #message%> </h1>
<%= select(:grade,:id,#distinct_grade_list,{},:onchange => "callGrade(this.value)")%>
<%= select(:period,:id,#distinct_period_list)%>
<%= select(:student_name,:id,#student_name_list,{},{ :multiple => true, :size => 4 }) %>
<br/>
<%= radio_button_tag(:age, :child,{},:onclick => "callMe(this.id)") %><%= label_tag(:age_child, :" General Curriculum") %>
<%= radio_button_tag(:age, :adult) %><%= label_tag(:age_adult, :"Common Core Standards") %>
<br/>
<div id="farzi" style="border: 3px solid red;margin-top: 20px">
<% form_tag('call_ajax', :method=>'post', :multipart => true) do %>
<p>
Subject:
<br />
<%= text_field_tag "subject" %>
</p>
<p>
Priority:
<br />
<%= select_tag("priority", options_for_select([['Critical', '1'],
['Important', '2'],['Standard','3']], '3')) %>
</p>
<p>
Describe your problem:
<br />
<%= text_area_tag "description", "", :size=>"50x20" %>
</p>
<p>
Add an attachment:
<br />
<%= file_field_tag "attachment" %>
</p>
<p>
<%= submit_tag 'Submit' %>
</p>
<% end %>
</div>
</body>
</html>
now when i execute the page , the page doent display any form ,
and when i check the page source , there is no form content inside the div with id= farzi
in the page source from browser it shows
<div id="farzi" style="border: 3px solid red;margin-top: 20px">
</div>
any explanation ??
Replace
<% form_tag('call_ajax', :method=>'post', :multipart => true) do %>
with this
<%= form_tag('call_ajax', :method=>'post', :multipart => true) do %>
The <%= is used to output data from ruby in html.erb. If you just execute first command, it will return the correct data, but it won't output anything in html.

Categories

Resources