Unable to use variable containing string in place of hardcoded string - javascript

I am setting up Stripe on my web app. Stripe seems to work fine when I hardcode a string such as 'test#test.com' into the email parameter. When I try to use the value from the input box however, the code does not execute properly. I do not get an error, the code just simply does not execute further. Here is my code:
form.addEventListener('submit', function (event) {
var user_email = document.getElementById('example1-email').value;
document.getElementById('output').innerHTML = user_email;
event.preventDefault();
stripe.createPaymentMethod({
type: 'card',
card: cardElement,
billing_details: {
email: user_email
},
}).then(stripePaymentMethodHandler);
});
function stripePaymentMethodHandler(result, email) {
if (result.error) {
} else {
// Otherwise send paymentMethod.id to your server
fetch('/checkout_stripe', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: user_email,
payment_method: result.paymentMethod.id
}),
}).then(function (result) {
return result.json();
}).then(function (customer) {
// The customer has been created
}).then(redirectfunc);
}
HTML:
<form id="subscription-form">
<div class="cell example example1" id="example-1" style="padding-left: 25%;padding-right: 25%;padding-top: 5%">
<br>
<fieldset>
<div class="row">
<label for="example1-name" data-tid="elements_examples.form.name_label">Name</label>
<input id="example1-name" data-tid="elements_examples.form.name_placeholder" type="text" placeholder="Jane Doe" required
autocomplete="name">
</div>
<div class="row">
<label for="example1-email" data-tid="elements_examples.form.email_label">Email</label>
<input id="example1-email" data-tid="elements_examples.form.email_placeholder" type="email" placeholder="janedoe#gmail.com"
required autocomplete="email">
</div>
<div class="row">
<label for="example1-phone" data-tid="elements_examples.form.phone_label">Phone</label>
<input id="example1-phone" data-tid="elements_examples.form.phone_placeholder" type="tel" placeholder="(941) 555-0123" required
autocomplete="tel">
</div>
</fieldset>
<fieldset>
<div class="row">
<div id="example1-card"></div>
</div>
<form id="subscription-form">
<div id="card-element" class="MyCardElement">
<!-- Elements will create input elements here -->
</div>
<!-- We'll put the error messages in this element -->
<div id="card-errors" role="alert"></div>
</fieldset>
<button type="submit" style="background-color: #27eb15">Subscribe</button>
</form>
This is just the stock code from Stripe, with me pulling in the string from the input box and trying to put it into the email param. Bizarrely, only a hardcoded string such as test#test.com allows the process to complete, but not just using the var user_email - despite that just being a string that contains the same string as the hardcoded.
I have tested whether or not I am actually pulling anything in when I use the .value, and I am. I have also tested the datatype of user_email, and it is indeed a string.
How can I get this to execute properly using the data pulled in from the user input boxes?

Related

Submitting Braintree form after getting payment nonce using hosted fields

I am trying to customize the layout of my Braintree payment form using hosted fields.
I had been using the JS v2 SDK but was having other issues: Braintree - Hosted Fields - Uncaught TypeError: FormNapper requires an HTMLFormElement element or the id string of one
I've tried changing to the v3 SDK.
Here is the stripped down version of my payment form and the braintree.js file that I am using with it:
$.ajax({
url:'web/token.php',
type:'get',
dataType:'json',
success:function(token){
var payment_form = document.querySelector('#payment_form');
var submit_button = document.querySelector('#payment_button');
braintree.client.create({
authorization: token
}, function(err, clientInstance) {
if (err) {
console.error(err);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {'font-size': '14px'},
'input.invalid': {'color': 'red'},
'input.valid': {'color': 'green'}
},
fields: {
number: {selector: '#card-number',placeholder: '4111 1111 1111 1111'},
cvv: {selector: '#cvv',placeholder: '123'},
expirationDate: {selector: '#expiration-date',placeholder: 'MM/YY'}
}
}, function(err, hostedFieldsInstance) {
if (err) {
console.error(err);
return;
}
submit_button.removeAttribute('disabled');
payment_form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
console.log('Got a nonce: ' + payload.nonce);
$('#payment-method-nonce').val(payload.nonce);
// payment_form.submit();
// $('#payment_form').submit();
document.getElementById('payment_form').submit();
});
});
});
});
}
});
<form action="process_order.php" method="POST" class="form" id="payment_form">
<div id="payment_container">
<div class="form-group">
<label for="card-number">Card Number</label>
<div id="card-number" name="card-number"></div>
</div>
<div class="form-group">
<label for="cvv">CVV</label>
<div id="cvv" name="cvv"></div>
</div>
<div class="form-group">
<label for="expiration-date">Expiration Date</label>
<div id="expiration-date" name="expiration-date"></div>
</div>
<input type="hidden" id="payment-method-nonce" name="payment-method-nonce">
<input type="submit" class="btn btn-default mx-auto" value="Complete Order ยป" id="payment_button">
</div>
</form>
<script src="https://js.braintreegateway.com/web/3.50.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.50.0/js/hosted-fields.min.js"></script>
<script src="web/braintree.js"></script>
At this point I can get the nonce and it is added to the value of the hidden input but the form won't submit.
When I use the variable name or use document.getElementById() I get TypeError: document.getElementById(...).submit is not a function but when I do it the jQuery way ($) nothing happens.

How can I send an array of values from the inputs to the controller

I've got a number of inputs in a form, created dynamically, and I'm trying to send them to the controller as an array using javascript.
Originally it was only one value and it was part of the Entity I pass in the model. Then, as it can be more than one, I added a Transient field to the entity as a List and also created another class in java with just a List. However, I still don't know how to add these values from javascript to the th:object in the form.
<form id="selectform" th:object="${systemIdListForm}" th:action="#{/myController}" method="get">
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function () {
$("#addMore").click(function() {
var html = '<div class="form-group col-md-1"><input class="form-control" name="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/></div>';
$('#fields').append(html);
});
$("#selectform").submit(function(){
var values = $(this).serialize();
});
});
/*]]>*/
</script>
At the moment I can see that the variable values have the right information but nothing is sent to the controller. I realize that the formatting of these values is probably not want I need but I'm not sure what to do.
Any help is much appreciated
What data type have you used in Model ?
Make sure you have taken String [] for that field.
If not taken String [] then use that and let me know whether it works or not.
Also you can take help of below code.It is for your case only.
$("#selectform").submit(function (event) {
// form redirect stop
event.preventDefault();
var status = jbf.form.validate('#selectform');
if (!status) {
return;
}
// get form data
var data = {};
data["enrollmentNumber"] = $("#enrollmentNumber").val();
data["systemIdInput"] = jQuery("#selectform input[name=systemIdInput]").val();
var url = "/yourURL";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
var message = response.message;
//success notification
if(response.success === true){
alert(message);
}else{
error(message);
}
},
error: function (e) {
console.log("ERROR: ", e);
error("Add failed");
}
});
});
I managed to get the list of values from all the inputs in the form using a hidden input. I added a transient field in my entity (systemIds) where I've got all the values.
<form id="selectform" th:object="${myEntiry}" th:action="#{/crops/singlecroplabeloffinsp/list/1}" method="get">
<input class="form-control" id="systemIdList" th:field="*{systemIds}" type="hidden"/>
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
...
$("#selectform").submit(function(){
//get all the system ids
var x = document.getElementsByName("systemIdInput");
var systemIds = [];
for (i = 0; i < x.length; i++ ) {
if (x[i].type ='text') {
systemIds.push(x[i].value);
}
}
$("#systemIdList").val(systemIds);
this.submit();
});
Added to the entity with getter & setter:
#Transient
private List<Integer> systemIds;

Trouble creating Stripe Token: 402 (Payment Required) error

Good day everyone,
Below is the error code that is thrown in console:
(index):3 POST https://api.stripe.com/v1/tokens 402 (Payment Required)
(index):3 POST https://api.stripe.com/v1/tokens 402 (Payment Required)c # (index):3e # (index):3a # (index):3Stripe.isDoubleLoaded.Stripe.xhr # (index):3Stripe.a._rawRequest # (index):2Stripe.a.request # (index):2Stripe.token.a.create # (index):2Stripe.card.b.createToken # (index):2Stripe.a._channelListener # (index):2incoming # (index):2f # (index):2
Below is the javascript code
// Generate the user token
$(function() {
// Once the user has submited the form
$(".submit").click(function(e) {
// Prevent the form from submiting by default
e.preventDefault();
// Ensure that checkbox is checked
if($('#checkbox').is(":checked")) {
// Prevent the form from submiting by default
var $form = $('#payment-form');
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
}
else {
// Display an error message to the user by writting directly into the header error tag
document.getElementById('checkboxError').innerHTML = "You must kindly accept the terms and conditions to continue.";
}
});
// Ensure that checkbox is checked
if($('#checkbox').is(":checked")) {
var appendedStripeToken = false;
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Scroll to the billing section
$("#billingError").scrollTop();
// 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;
handleCall(token);
}
// What to do after the token has been generated.
function handleCall(token) {
var $form = $('#payment-form');
if (!appendedStripeToken) {
// Insert the token into the form so it gets submitted to the server
appendedStripeToken = true;
phpCall();
}
}
// Post the package name, the token, and the user name information to the billing.php page
function phpCall() {
if( appendedStripeToken === true ){
$.ajax({
type: "POST",
data: {run: true, packageName: $('#packageName').val(), token: token, userName: $('#userName').val(),customerName: $('#customerName').val() },
url: '/app/functions/billing.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
$('#payment-form').prop('disabled', true); // TODO: give your html-submit-input-tag an "id" attribute
window.location = response;
}
});
}
}
}
}
});
Below is the HTML code
<!-- Package name to be submitted to server -->
<input type="hidden" id="packageName" value="{{ packageName|capitalize }}">
<!-- Username to be submitted to server -->
<input type="hidden" id="userName" value="{{ userName }}">
<input type="hidden" id="customerName" value="{{ customerName }}">
<div class="form-row">
<label for="cardHolder">Cardholder Name</label><br>
<input type="text" id="cardHolder" size="20" data-stripe="name">
</label>
</div>
<br><br>
<div class="form-row">
<label for="cardNumber">Card Number </label><br>
<input type="text" id="cardNumber" size="20" data-stripe="number">
</label>
</div>
<br>
<img src="/public/images/credit-card/visa.png" class="card-visa">
<img src="/public/images/credit-card/mastercard.png" class="card-mastercard">
<img src="/public/images/credit-card/american-express.png" class="card-aexpress">
<br>
<div class="form-row">
<label for="cardExpiration"> Expiration (MM/YY)</label><br>
<input class="expirationNumber" type="text" size="2" id="cardExpiration" data-stripe="exp_month">
</label>
<span> / </span>
<input class="expirationNumber" type="text" size="2" data-stripe="exp_year">
</div>
<br><br>
<div class="form-row">
<label for="cardCVC">CVC</label><br>
<input type="text" id="cardCVC" size="4" data-stripe="cvc">
</label>
</div>
</div>
</div>
<input type="checkbox" id="checkbox">
<label for="checkbox">By purchasing this package you are agreeing to our Terms & Conditions</label><br><br>
<h4 id="checkboxError"></h4>
<button type="submit" class="submit btn-tangerine">Submit Payment</button>
</form>
Any help would be greatly appreciated!
I thnk that the main error lies in the following line:
Stripe.card.createToken($form, stripeResponseHandler);
What is suppose to happen is really simple. Token gets created when all proper information are given, and then the token along with other information are posted via ajax to the server where a PHP code will create the charge using these information.
I was facing same issue when I add test API KEYS for payment, then site was working fine and when I add live key then site shows same error on console.
But problem was, I was testing live key with test credit card number. May be you were doing same mistake
And sorry for bad English.

angular payments returns invalid card with test data

I'm trying to congifure stripe in angular js using the angular-payments app found here
https://github.com/laurihy/angular-payments
the problem is that it seems to be returning invalid_card errors even with the test data.
Here is the error:
POST https://api.stripe.com/v1/tokens 402 (Payment Required)
Stripe.isDoubleLoaded.c(index):3 Stripe.isDoubleLoaded.e(index):3 Stripe.isDoubleLoaded.a(index):3 Stripe.isDoubleLoaded.Stripe.xhr(index):2 Stripe.a._rawRequest(index):2 Stripe.a.request(index):2 Stripe.token.a.create(index):2 Stripe.card.b.createToken(index):2 Stripe.a._channelListener(index):2 Stripe.isDoubleLoaded.H.Socket.t.concat.incoming(index):2
I'm setting my publishable key and including Stripe.js without a problem, and I know that the call is completed, as I'm picking up the error in the ResponsHandler
any thoughts what may be causing this?
here is the code:
form
<form name="myform" id="signup-form" stripe-handler="saveCustomer">
<div class="form-group">
<label for="card_number">Card Number</label>
<input type="text" class="form-control" size="20" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="myform.number.$card.type"/>
</div>
<div class="form-row">
<label for="CVC"> CVC</label>
<input type="text" class="form-control" size="4" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type"/>
</div>
<div class="form-row">
<label for="expiry"> Expiry</label>
<input type="text" class="form-control" size="2" ng-model="expiry" payments-validate="expiry" payments-format="expiry" />
</div>
<div class="text-center">
<span class="glyphicon glyphicon-heart"></span>
<h3>Thanks For Your Money!</h3>
<button type="submit" class="btn">Submit</button>
</div>
here is the contoller function:
// function to process the form
$scope.saveCustomer = function(status, response) {
if (response.error) {
// Show the errors on the form
console.log(response);
console.log(response.error);
} else {
// response contains id and card, which contains additional card details
var token = response.id;
console.log(token);
formData.token = token;
}
}
and my index.html header includes...
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('my-key-here');
// ...
</script>
The wierd thing is that it was working with stripe-angluar which is another repo for processing stripe - any ideas what am i doing wrong?
You might be creating the token incorrectly. I was having the same problem. What worked for me was setting the card like this:
Stripe.card.createToken({
"number": '4242424242424242',
"exp_month": 12,
"exp_year": 2016,
"cvc": '123'
}, function(status, response) {
stripeResponseHandler(status, response);
});
Instead of this (notice how the card object is created twice - thus the "Stripe.isDoubleLoaded" error, I believe ):
Stripe.card.createToken({
card: {
"number": '4242424242424242',
"exp_month": 12,
"exp_year": 2016,
"cvc": '123'
}
}, function(status, response) {
stripeResponseHandler
});

Sending form data to Parse.com

I have a form that I created and I want to send that form information to a backend database called Parse.com. I create the table in Parse with the same names as the fields on the form, but I'm not sure how to send it to Parse using js.
<form id="contact-form" class="contact-form" method="post" action="" onSubmit="return checkMail()" name="validation">
<div class="form-group row" id="price">
<div class="col-lg-4">
<input type="text" name="fname" class="form-control" id="name" placeholder="First *" required >
</div>
<div class="col-lg-4">
<input type="text" name="lname" class="form-control" id="name" placeholder="Last *" required>
</div>
<div class="col-lg-4">
<input type="text" name="email" class="form-control" id="name" placeholder="E-mail *" required>
</div>
</div>
</div>
<div class="form-group row" align="center">
<div class="col-lg-12" align="center">
<button type="submit" class="button default">SEND <i class="glyphicon glyphicon-send"></i></button>
</div>
</div>
Attach your parse object save function to the form submit. This can be achieved with ease by using JQuery.
Next you have to capture the form input data, then save it to your Parse object.
This script assumes you have created a class in parse with the [string] columns of fname, lname and email.
<script>
Parse.initialize("API KEY", "JAVASCRIPT KEY");
var ParseObj = Parse.Object.extend('myClass'); //create local parse object from your Parse class
$('#contact-form').submit(function(e) {
//on form submit
e.preventDefault();
//get data from form
var data = {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val()
};
//create new Parse object
parseObj = new ParseObj();
//match the key values from the form, to your parse class, then save it
parseObj.save(data, {
//if successful
success: function(parseObj) {
alert(parseObj.get('fname') + " " + parseObj.get('lname') + " " + parseObj.get('email') + " saved to Parse.")
}
,
error: function(parseObj, error) {
console.log(parseObj);
console.log(error);
}
}
);
});
</script>
This is a typical "too broad" question, as you're not really having a specific problem but just asking us to write the code for you. Best I can do is point you to the parse.com user guide which shows you how you can do this. Check it out, try it for yourself and then ask here again if you have specific issues with the code.
Example snipped from the user guide found here: https://parse.com/docs/js_guide#objects-saving
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.set("score", 1337);
gameScore.set("playerName", "Sean Plott");
gameScore.set("cheatMode", false);
gameScore.save(null, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});

Categories

Resources