Rails 4 Stripe API only working on Refresh - javascript

I thought I had the stripe API working. However when I deployed it to Heroku I found that I had to 'refresh' my page or else I would get a javascript in the console when visiting my charging form. The error was
ReferenceError: Stripe is not defined
Now when I refresh the same page this error dissapears and I can continue with my payments. I am not that knowledgeable on JS so that may be the problem I suspect. I have tried adding other stripe libraries but no avail. My code for the form is below:
<h4>Begin your $5.00 a month subscription</h4>
<form action="/users/charge" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="row">
<div class="col-md-6">
<label>Card Number</label>
<input class="form-control" type="text" name="Card Number" size="20" data-stripe="number" placeholder="4242424242424242"/>
</div>
</div>
<br />
<div class="row">
<div class="col-xs-2">
<label>CVC</label>
<input type="text" data-stripe="cvc" class="form-control" name="CVC" placeholder="123">
</div>
</div>
<br />
<div class="row">
<div class="col-xs-2">
<label>Expiration</label>
</div>
</div>
<div class="row">
<div class="col-xs-4">
<label>MM</label>
<input type="text" data-stripe="exp-month" class="form-control" name="MM" placeholder="01">
</div>
<div class="col-xs-4">
<label>YYYY</label>
<input type="text" data-stripe="exp-year" class="form-control" name="YYYY" placeholder="2020">
</div>
</div>
<div class="row">
<div class="col-xs-4">
<br/><button class="btn btn-primary" type="submit">Create Subscription</button>
</div>
<div class="col-xs-4">
<br/>
<%= link_to image_tag("big.png"), "https://stripe.com/" %>
</div>
<div class="col-xs-4">
<br/>
<ul>
<li>Reasons To Subscribe:</li>
<li>More tutorials</li>
<li>Personal Contact with A.J.</li>
<li>Request Your own tutorials!</li>
<li>Open Source Help</li>
</ul>
</div>
</div>
<%= token_tag nil %>
</form>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey("<%= ENV['STRIPE_PUBLIC_KEY'] %>");
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Show the errors on the form:
$form.find('.payment-errors').text(response.error.message);
$form.find('.submit').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
// Insert the token ID into the form so it gets submitted to the server:
$form.append($('<input type="hidden" name="stripeToken">').val(token));
// Submit the form:
$form.get(0).submit();
}
};
$(function() {
var $form = $('#payment-form');
$form.submit(function(event) {
// Disable the submit button to prevent repeated clicks:
$form.find('.submit').prop('disabled', true);
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
});
});
</script>

This may be due to Turbolink
Change 'data-turbolinks-track' => false infollowing lines in your application.html.haml or application.html.erb file in views/layouts folder.
%meta{:content => "width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no", :name => "viewport"}/
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => 'reload'
= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload'
= csrf_meta_tags
so your code becomes:
%meta{:content => "width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no", :name => "viewport"}/
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => false
= javascript_include_tag 'application', 'data-turbolinks-track' => false
= csrf_meta_tags

I had this right before my checkout page: <a href='/my/checkout'>Purchase Subscription</a>
I had to add data-no-turbolink='true' to the tag:
<a href='/my/checkout' data-no-turbolink='true'>Purchase Subscription</a>

Related

How to set text_field required attribute false to submit the form using Ruby on Rails

I'm trying to submit a form with a looped text_field. But whenever I click the submit button, nothing is happening. The VIP name text_field is displaying whenever the user click the VIP discount from the discount dropdown. For each VIP ticket, there's a field for VIP name. The text_field is required. I'm trying to submit it by clicking the Purchase button. Maybe the required field on the hidden text_Field is taking effect that's why the form can't submit yet. I tried to implement the javascript .removeAttribute("required") and the .required = false; whenever the text_field is hidden but it didn't work as well. What's your thought?
<%= f.fields_for :movie_tickets do |mtf| %>
<div class="row text-center">
<label>============================ <%= "TICKET " + #count.to_s %> =============================</label> <br> <br>
<b> SEAT NO: <%=mtf.object.seat.name%> | ORIGINAL PRICE: <label class="label_original_prices"><%= number_to_currency mtf.object.net_price, unit:'' %></label> | DISCOUNTED PRICE: <label class="label_discounted_prices" id="pricediscount<%=#count%>">No Discount</label> </b> <br> <br>
</div>
<div class="form-group">
<div class="col-md-3">
<label>DISCOUNT :</label>
</div>
<div class="col-md-9">
<%= mtf.select :discount_id, options_from_collection_for_select(discounts, :id,:name),{include_blank:true}, class:"form-control", id:"discount"+#count.to_s, onchange:"getDisc(this)" %>
</div>
</div>
<br><br>
<div class="form-group" style="display: none;" id="divVIP<%=#count%>">
<div class="col-md-3">
<label>VIP NAME :</label>
</div>
<div class="col-md-9">
<%= mtf.text_field :vip_name , placeholder: "Type VIP name here...",class: "form-control", required: true %>
</div>
</div>
<% #count += 1 %>
<% end %>
<script type="text/javascript">
if(getValueDiscount == "9") {
document.getElementById('divVIP' + count).style.display = "block";
}else {
document.getElementById('divVIP' + count).style.display = "none";
}
</script>
Remove the required: true or set it to false in the below line:
<%= mtf.text_field :vip_name , placeholder: "Type VIP name here...",class: "form-control", required: true %>

Add more fields to form dynamically in Rails

I have a button that adds a partial to my form. The partial is additional form fields using fields_for
The main form is for creating a Project and the fields_for are for creating a RewardsTier model that belongs to the Project
Everything works for adding one additional RewardsTier, but when I add more than one additional RewardsTier form they all have the same name in the html: project[rewards_tiers_attributes][1][min_amount]. I think I just need the integer value to increment, but am not sure how to do this
#_rewards_tier_form.html.erb
<div class="tier-creation-div">
<%= f.fields_for :rewards_tiers do |r| %>
<label for="min_amount">Tier Amount</label>
<%= r.text_field :min_amount, data: {name: 'min_amount'}, class: "w-input", id: "min_amount", maxlength: "256", placeholder: "$1", required: "required", autofocus: 'true' %>
<label for="body">Tier Body</label>
<%= r.text_area :body, data: {name: 'body'}, class: "w-input", id: "body", maxlength: "5000", placeholder: "We email you the show notes and links...", required: "required", autofocus: 'true' %>
<% end %>
</div>
.
#new.html.erb
<%= form_for(#project, data: {name: "Email Form 2"}, html: {class: 'w-clearfix', id: "email-form-2", name: "email-form-2"}, url: '/projects/create', method: 'post' ) do |f| %>
...
<div class="rewards-creation-div" id="rewards-creation-div">
<h4>Rewards</h4>
<%= render 'rewards_tier_form', f: f %>
</div>
<div>
<a class="add-tier-button w-button" id="add-tier-button" href="#">+ Add tier</a>
<script type="text/javascript">
$('#add-tier-button').click(function() {
$("#rewards-creation-div").append('<%= escape_javascript("#{render 'rewards_tier_form', f: f}").html_safe %>');
});
</script>
</div>
...
<input class="submit-project-button w-button" data-wait="Please wait..." type="submit" value="Create Project"><a class="cancel-button w-button" href="#">Cancel</a>
<% end %>
This can't be done in Rails because it's all rendered client side. I got around this by using Javascript. My JS isn't great, so there is probably a cleaner way of writing it, but it works.
#_rewards_tier_form.html.erb
<div class="tier-creation-div">
<script>
document.getElementById("rewards-creation-div").lastElementChild.insertAdjacentHTML('beforeend','<label for="min_amount">Tier Amount</label>');
document.getElementById("rewards-creation-div").lastElementChild.insertAdjacentHTML('beforeend','<input data-name="min_amount" class="w-input" id="min_amount" maxlength="256" placeholder="$1" required="required" autofocus="autofocus" size="256" type="text" name="project[rewards_tiers_attributes]['+rewards_tier_index+'][min_amount]">');
document.getElementById("rewards-creation-div").lastElementChild.insertAdjacentHTML('beforeend','<label for="body">Tier Body</label>');
document.getElementById("rewards-creation-div").lastElementChild.insertAdjacentHTML('beforeend', '<textarea data-name="body" class="w-input" id="body" maxlength="5000" placeholder="We email you the show notes and links..." required="required" autofocus="autofocus" name="project[rewards_tiers_attributes]['+rewards_tier_index+'][body]"></textarea>');
</script>
</div>
.
#new.html.erb
<div class="rewards-creation-div" id="rewards-creation-div">
<h4>Rewards</h4>
<script type="text/javascript">
var rewards_tier_index = 0;
</script>
<%= render 'rewards_tier_form', f: f %>
</div>
<div>
<a class="add-tier-button w-button" id="add-tier-button" href="#">+ Add tier</a>
<script type="text/javascript">
$('#add-tier-button').click(function() {
rewards_tier_index = rewards_tier_index + 1;
$("#rewards-creation-div").append('<%= escape_javascript("#{render 'rewards_tier_form', f: f, child_index: #indx}").html_safe %>');
});
</script>
</div>

Stripe::InvalidRequestError (This customer has no attached payment source)

There seems to be a problem with sending customer data and token back to Stripe's server. I'm currently using the test api to make dummy transactions. But, I cannot get past this point for no reason at all. I've tried everything to fix this error. I will post the code and error message below.
Subscriptions_Controller.rb
class SubscriptionsController < ApplicationController
before_filter :authenticate_user!, except: [:new]
before_action :redirect_to_signup, only: [:new]
def show
end
def new
#subscription = current_user.subscription
if #subscription.active
#stripe_customer = Stripe::Customer.retrieve(#subscription.stripe_user_id)
#stripe_subscription = #stripe_customer.subscription.first
end
end
def create
token = params[:stripeToken]
customer = Stripe::Customer.create(
:source => token,
:plan => "gbsubscriptionlevel1",
:email => current_user.email
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_subscription_path
current_user.subscription.stripe_user_id = customer.id
current_user.subscription.active = true
current_user.subscription.save
redirect_to users_index_path
end
def cancel_subscription
#stripe_customer = Stripe::Customer.retrieve(
current_user.subscription.stripe_user_id
)
#stripe_subscription = #stripe_customer.subscription.first
end
private
def redirect_to_signup
if !user_signed_in?
session["user_return_to"] = new_subscription_path
redirect_to new_user_registration_path
end
end
end
_stripe_form.html.erb
<div class="container">
<%= form_tag subscription_path, id: 'payment-form' do %>
<form action="/subscription" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="row">
<div class="col-xs-4">
<label>
<span>Card Number</span>
<input value="4242 4242 4242 4242" class="form-control" type="text" size="20" data-stripe="number"/>
</label>
</div>
</div>
<div class="row">
<div class="col-xs-1">
<label>
<span>CVC</span>
<input value="123" class="form-control" type="text" size="4" data-stripe="cvc"/>
</label>
</div>
</div>
<div class="row">
<div class="col-xs-1">
<label>MM</label>
<input value="12" class="form-control" type="text" size="2" data-stripe="exp-month" placeholder="01"/>
</div>
<div class="col-xs-1">
<label>YYYY</label>
<input value="2019" class="form-control" type="text" size="3" data-stripe="exp-year" placeholder="2020"/>
</div>
</div>
<div class="row">
<div class="col-xs-1">
<br/>
<button class="btn btn-primary-outline" type="submit">Create Subscription</button>
</div>
</div>
</form>
<% end %>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
</div>
subscription.js
Stripe.setPublishableKey('pk_test_tmBNNUvHTmtWXLhSL1q647iH');
function stripeResponseHandler(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// response contains id and card, which contains additional card details
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
}
jQuery(function ($) {
$('#payment-form').submit(function (event) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
stripe.rb
Stripe.api_key = ENV["STRIPE_API_TEST_SECRET_KEY"]
That response typically arises after you try to attach a Subscription to someone with no card token attached. From your code, I'd hazard a guess that you're running into a CardError and then despite that, trying to attach a Subscription anyway, which will not work.

Update database from bootstrap modal using AJAX

I am creating a page which displays some records from the database (please refer to the screen shots). Each row has an edit button which opens up a bootstrap modal for inputing comments and changing the user's status. On clicking the done button, I have to update the changes in the database preferably using AJAX. However it's not properly working. I can't seem to understand what's going wrong.
This is my jsp page...
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.util.ArrayList"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<%
String loginIdEdit = "";
%>
**<script>
$(function() {
//twitter bootstrap script
$("button#save").click(function(e) {
$.ajax({
type : "POST",
url : "defaulterUpdater.jsp",
data : $('form.contact').serialize(),
success : function(msg) {
},
error : function() {
alert("Failed");
}
});
});
});
</script>**
<script type="text/javascript">
function myFun() {
alert("welcome");
var demo = document.createElement('div');
demo.innerHTML = demo.innerHTML
+ "<tr><input type='text' name='mytext'><tr>";
}
</script>
</head>
<body>
<div class="container">
<form method="post" action="RegistrationServlet">
<%
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
Connection con = null;
con = DBManager.getConnection();
Statement st = con.createStatement();
String userName = "";
ArrayList<AutoDefaulterVO> defaulterList = null;
HttpSession session2 = request.getSession();
if (session2.getAttribute("first_name") == null) {
out.println("Your session expired.....");
%>
Please Login Again to continue
<%
} else {
defaulterList = (ArrayList<AutoDefaulterVO>) session2
.getAttribute("autoDefaulterList");
userName = session2.getAttribute("first_name").toString();
%>
<form action='LogoutServlet' method=POST>
<table align="right" style="width: 100%">
<tr>
<td align="left"><input type="submit" name="logout"
value="Home" onclick="form.action='AdminHome';">
</td>
<td align="right"><input type="submit" name="logout"
value="Logout" onclick="form.action='LogoutServlet'">
</td>
</tr>
</table>
</form>
<h3 align="center">Auto Defaults</h3>
<table border="1" style="width: 100%">
<br>
<br>
<h3 align="center">
Welcome
<%=userName%></h3>
<table border="1" style="width: 100%" class="table table-hover">
<tr>
<th>Default Status</th>
<th>Borrower Name</th>
<th>Borrower Rating</th>
<th>Accural Status</th>
<th>Bank Number</th>
<th>Account Number</th>
<th>Days Past Due</th>
<th>Comments</th>
</tr>
<%
for (int i = 0; i < defaulterList.size(); i++) {
AutoDefaulterVO defaulter = new AutoDefaulterVO();
defaulter = defaulterList.get(i);
loginIdEdit = defaulter.getDefaulterLoginID();
System.out.println("Printing only auto defaulter in jsp ");
%>
<tr>
<%-- <td><%=defaulter.getDefaultStatus()%></td> --%>
<td>Auto Defaulter</td>
<td><%=defaulter.getBorrowerName()%></td>
<td><%=defaulter.getBorrowerRating()%></td>
<td><%=defaulter.getAccuralStatus()%></td>
<td><%=defaulter.getBankNumber()%></td>
<td><%=defaulter.getAccountNumber()%></td>
<td><%=defaulter.getDaysPastDue()%></td>
<%-- <td><%=loginIdEdit%></td> --%>
<td>
<%
ResultSet rs = st
.executeQuery("select * from aip_comments");
while (rs.next()) {
System.out.println("Auto defaulter loginId printing-->"
+ defaulter.getDefaulterLoginID());
String loginId = rs.getString("login_id");
System.out.println("databse loginId printing-->"
+ rs.getString("login_id"));
if (defaulter.getDefaulterLoginID().equals(
rs.getString("login_id"))) {
%> <%=rs.getString("comments")%> <%
}
}
%>
</td>
<td>
<!-- <form name="editForm" action="edit.jsp">
<button type="button" data-toggle="modal" class="btn btn-default" data-target="#myModal">Edit</button>
-->
<form class="contact">
<button href="#edit-modal" type="button" data-toggle="modal"
class="btn btn-default" data-target="#<%=loginIdEdit %>">Edit</button>
<!-- <a data-toggle="modal" data-target="#<%=loginIdEdit%>" href="#">Edit</a> -->
<!-- <input type="submit" name="editButton" value="Edit"> -->
<!--<input type="hidden" id="edit" name="edit" value="<%=loginIdEdit%>" />-->
</td>
<div class="modal fade" id="<%=loginIdEdit%>" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">
Edit status and add comment for
<%=defaulter.getBorrowerName()%></h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="sel1"><span></span>Select status:</label> <select
class="form-control" id="sel1" name="sel1">
<option>Validate Error</option>
<option>Auto Weaver</option>
<option>ReDefault</option>
</select>
</div>
<div class="form-group">
<label for="defaultercomment"><span></span>Add
comment:</label> <input type="text" class="form-control"
name="defaultercomment" id="defaultercomment"<%-- value="<%=loginIdEdit%>" --%>>
</div>
</div>
<div class="modal-footer">
<button type="button" id="save" name="save"
class="btn btn-default" data-dismiss="modal" align="centre">Done</button>
</div>
</div>
</div>
</div>
</form>
<%
}
%>
</tr>
</table>
<%
}
%>
</body>
</html>
ajax URL redirects to below jsp page,defaulterUpdater.jsp where I only print the values to see if they're correctly retrieved.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% String selection = request.getParameter("sel1");
String comment = request.getParameter("defaultercomment");
System.out.println("selection-"+selection+"comment--"+comment);
%>
</body>
</html>
The values are accepted only for the first row..For rest of the rows null values are being printed. Any help will be appreciated. Thanks!
I got the code working. Basically needed an unique identifier for "done" button as is rule of javascript. Hence it was not working for all rows.
I gave unique id's to the form
and by submitting called the onclick method..
onClick="callAjax(this.form)"
So now it's working. Thank you all for your help!
You are putting the modal wrong inside the table. By table syntax it is wrong. You must put this modal out from the table and call ajax inside the shown.bs.modal event of bootstrap.
As you need to repeat buttons. Keep a hardwired id of the button which will open the modal, also keep an data-attribute-id to uniquely identify the button clicked which will help you to get details about which button clicked in the list(as buttons are repeating for each row, your data-attribute-id will be loginid of the row).
Then write jquery with event shown.bs.modal, like
$("#modalId").on("shown.bs.modal", function(e){
var btnClicked= $(e).relatedTarget();
var btnClickedId= btnClicked.data("attribute-id"); // id of clicked button
// here more code see attached link below for more
}
I have posted a similer answer previously in asp.net mvc but you will have idea as situation is similer to you.
Please visit my answer on question dynamically created bootstrap3 modals do not work
Hope it will help to get idea to resolve this.
#Update Section Removed your some code for clean view
<script type="text/javascript">
$(document).ready(function () {
$('#editModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);//Button which is clicked
var clickedButtonId= button.data('loginidedit');//Get loginidedit of the button or get other variable same
$("#loginid").val(clickedButtonId);//Put here id of the btn clicked which has attribute for loginidedit
//you can get here other required filed or make ajax call to get other values formt he database for this loginidedit.
})
});
</script>
<body>
<div class="container">
//Table here
<table border="1" style="width: 100%" class="table table-hover">
<%
for (int i = 0; i < defaulterList.size(); i++) {
AutoDefaulterVO defaulter = new AutoDefaulterVO();
defaulter = defaulterList.get(i);
loginIdEdit = defaulter.getDefaulterLoginID();
System.out.println("Printing only auto defaulter in jsp ");
%>
<tr>
<td>
<button href="#edit-modal" type="button" data-toggle="modal"
class="btn btn-default" data-target="#editModal" data-loginidedit = "<%=loginIdEdit %>">Edit</button>
</td>
</tr>
<%
}
%>
</table>
//Modal here
<div class="modal fade" id="editModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
</div>
<form class="contact"> //give action, method attribute here or make ajax call on save button clicked,
<input type="hidden" name="????" id="loginid">// the modal on shown will fill this value.
<div class="modal-body">
<div class="form-group">
<label for="sel1"><span></span>Select status:</label> <select
class="form-control" id="sel1" name="sel1">
<option>Validate Error</option>
<option>Auto Weaver</option>
<option>ReDefault</option>
</select>
</div>
<div class="form-group">
<label for="defaultercomment"><span></span>Add
comment:</label> <input type="text" class="form-control"
name="defaultercomment" id="defaultercomment"<%-- value="<%=loginIdEdit%>" --%>>
</div>
</div>
<div class="modal-footer">
<button type="button" id="save" name="save"
class="btn btn-default" data-dismiss="modal" align="centre">Done</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
$(function() {
//twitter bootstrap script
$("button#save").click(function(e) {
$.ajax({
type : "POST",
url : "defaulterUpdater.jsp",
data : $('form.contact').serialize(),
success : function(msg) {
},
error : function() {
alert("Failed");
}
});
});
});

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