PayPal Checkout JS SDK - dynamically setting an amount - paypal

I'm using following js code to show paypal button on a page.
I add two radio button to select amount of payment, but I can't set it.
I save amount in variable named importoSelezionato.
But if I replace 50 with variabled,it not work.
How replace correctly number in purchaseunit with variable?
Thanks
<script>
function initPayPalButton() {
// Radiobutton IMPORTO $(document.getElementsByName('CustImporto')).on('click',function(){
var getSelectedValue = document.querySelector( 'input[name="CustImporto"]:checked');
//alert("importo selezionato: euro "+getSelectedValue.value);
var importoSelezionato = getSelectedValue.value;
});
// Radiobutton IMPORTO
paypal.Buttons({
style: {
shape: 'rect',
color: 'gold',
layout: 'horizontal',
label: 'pay',
},
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{"description":"Ricarica standard account","amount":{"currency_code":"EUR","value":50}}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
// Full available details
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
// Show a success message within this page, e.g.
const element = document.getElementById('paypal-button-container');
element.innerHTML = '';
element.innerHTML = '<h3>Thank you for your payment!</h3>';
//aggiungere un log in una tabella di database
// Or go to another URL: actions.redirect('thank_you.html');
});
},
onError: function(err) {
console.log(err);
}
}).render('#paypal-button-container');
}
initPayPalButton();
</script>
<div class="row">
<div class="col-lg-6 in-gp-tl">
<div class="input-group">
<span class="input-group-addon">
<input type="radio" name="CustImporto" required="" value="25" aria-label="...">
</span>
<input type="text" class="form-control" readonly="readonly" value="25" aria-label="...">
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
<div class="col-lg-6 in-gp-tb">
<div class="input-group">
<span class="input-group-addon">
<input type="radio" name="CustImporto" required="" value="50" aria-label="...">
</span>
<input type="text" class="form-control" readonly="readonly" value="50" aria-label="...">
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->

Query the DOM from createOrder, which runs when a PayPal button is clicked. No need for an onclick listener...
<script>
function initPayPalButton() {
function getAmount() {
var getSelectedValue = document.querySelector( 'input[name="CustImporto"]:checked');
//alert("importo selezionato: euro "+getSelectedValue.value);
return getSelectedValue.value;
};
paypal.Buttons({
style: {
shape: 'rect',
color: 'gold',
layout: 'horizontal',
label: 'pay',
},
createOrder: function(data, actions) {
return actions.order.create({
"purchase_units": [
{
"amount": {
"currency_code": "EUR",
"value": getAmount()
},
"description": "Ricarica standard account"
}
]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
// Full available details
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
// Show a success message within this page, e.g.
const element = document.getElementById('paypal-button-container');
element.innerHTML = '';
element.innerHTML = '<h3>Thank you for your payment!</h3>';
//aggiungere un log in una tabella di database
// Or go to another URL: actions.redirect('thank_you.html');
});
},
onError: function(err) {
console.log(err);
}
}).render('#paypal-button-container');
}
initPayPalButton();
</script>

Related

Paypal paylater set button amount

I have a paypal page that accepts paypal pay later. I want to dynamically set the button amount with javascript.
This is the code
<script src="https://www.paypal.com/sdk/js?client-id=&currency=GBP&enable-funding=paylater,card&components=messages,buttons">
</script>
<div id="paypal-button-container"></div>
<script>
var amount = 90;
//$('#paypal').data('pp-amount',amount);
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: amount
}
}]
});
},
//return url after successful payment
onAuthorize: function(data, actions) {
console.log(data, actions);
actions.payment.execute().then(function(data) {
console.log(data);
// Show a success page to the buyer
});
}
}).render('#paypal-button-container');
</script>
<div id="paypal" data-pp-message data-pp-amount="90"> </div>
I added the paypal id into this <div id="paypal" data-pp-message data-pp-amount="90"> </div>
I am trying to dynamically set this value
data-pp-amount="90"
but this doesn't work $('#paypal').data('pp-amount',amount);
I did it this way
<script src="https://www.paypal.com/sdk/js?client-id=&currency=GBP&enable-funding=paylater,card&components=messages,buttons">
</script>
<div id="paypal-button-container"></div>
<div class="pp-message"> </div>
<script>
var am = 90;
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: am
}
}]
});
},
//return url after successful payment
onAuthorize: function(data, actions) {
console.log(data, actions);
actions.payment.execute().then(function(data) {
console.log(data);
// Show a success page to the buyer
});
}
}).render('#paypal-button-container');
paypal.Messages({
amount: am,
placement: 'product',
style: {
layout: 'text',
logo: {
type: 'primary',
position: 'top'
}
}
})
.render('.pp-message');
</script>

collections2 and meteor-cfs-autoform to upload and display image

I am using collections2 and meteor-cfs-autoform for schemas and to upload and display image using cfs:gridfs storage adaptor package but unable to show images in template.Can you please tell me where i am doing mistake and its solution.
collections.js
Recipes = new Mongo.Collection('recipes');
Reviews = new Mongo.Collection('reviews');
RecipesImages = new FS.Collection("recipesImages", {
stores: [new FS.Store.GridFS("recipesImages")]
});
RecipesImages.allow({
insert: function(userId, doc) {
return true;
},
update: function(userId, doc, fieldNames, modifier) {
return true;
},
download: function(userId) {
return true;
},
fetch: null
});
Recipes.attachSchema(new SimpleSchema({
name: {
type: String,
label: "Recipe Name",
max: 100
},
ingredients: {
type: [Object],
minCount: 1
},
"ingredients.$.name": {
type: String
},
"ingredients.$.amount": {
type: String
},
description: {
type: String,
label: "How to prepare ",
},
time: {
type: Number,
label: "Time (Minutes)",
},
image: {
type: String,
autoform: {
afFieldInput: {
type: "cfs-file",
collection: 'recipesImages',
label: 'Recipe Picture'
}
}
}
}));
recipes.js
Template.recipes.helpers({
'showRecipes':function(){
return Recipes.find();
},
'images': function () {
return RecipesImages.findOne({_id:id}) ;
}
})
recipes.html
<template name="recipes">
{{#each showRecipes}}
<div class=" col-md-4">
<div class="panel panel-default mb " >
<div class="panel-image">
<img src="{{this.url }}" class="panel-image-preview" />
</div>
<div class="panel-body">
<h4>{{name}}</h4>
<p>{{description}}</p>
</div>
<div class="panel-footer text-center" >
<p>its footer </p>
</div>
</div>
</div>
{{/each}}
</template>
Are you importing cfs:ui? If not, you should include it so that you can use the FS.GetFile helper. Then you can use this code.
Recipes Template
<template name="recipes">
{{#each showRecipes}}
<div class=" col-md-4">
<div class="panel panel-default mb " >
<div class="panel-image">
{{#with FS.GetFile "recipesImages" image}}
<img src="{{url}}" class="panel-image-preview" />
{{/with}}
</div>
<div class="panel-body">
<h4>{{name}}</h4>
<p>{{description}}</p>
</div>
<div class="panel-footer text-center" >
<span class="glyphicon glyphicon-open-file"></span>
</span><small> {{time}}</small>
<span class="glyphicon glyphicon-heart likes" style="vertical-align:middle"></span><small>2 </small>
<span class="glyphicon glyphicon-share"></span>
</div>
</div>
</div>
{{/each}}
</template>
Recipes helpers
Template.recipes.helpers({
'showRecipes':function(){
return Recipes.find();
}
});
Here's the link to cfs:ui documentation

react.js - show a message on and after form submission

On submitting the form, I want to show 'Please wait ..' and on successful submission the data returned from server. Using jQuery , it is easy to do. But there should be a React way as React does not like such kind of direct DOM manipulation - I think . 1) Am I right ? 2) How to show the message on (not after ) form submission?
var FormComp = React.createClass({
handleSubmit:function(){
var userName=this.refs.userName.getDOMNode().value.trim();
var userEmail= this.refs.userEmail.getDOMNode().value.trim();
if(!userName || !userEmail){
return;
}
this.props.onFormSubmit({userName:userName, userEmail:userEmail,url:"/api/submit"});
this.refs.userName.getDOMNode().value='';
this.refs.userEmail.getDOMNode().value='';
return;
},
render: function() {
var result=this.props.data;
return (
<div className={result}>{result.message}</div>
<form className="formElem" onSubmit={this.handleSubmit}>
Name: <input type="text" className="userName" name="userName" ref="userName" /><br/>
Email: <input type="text" className="userEmail" name="userEmail" ref="userEmail" /><br/>
<input type="submit" value="Submit" />
<form >
</div>
);
}
});
var RC= React.createClass({
getInitialState: function() {
return {data: ""};
},
onFormSubmit:function(data){
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: data,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render:function(){
return <FormComp onFormSubmit={this.onFormSubmit} data={this.state.data}/>
}
});
React.render(
<RC/>,
document.getElementById('content')
);
This is definitely something React can handle, no direct DOM manipulation is needed. You're almost there, just need to reorganize a little. Here's one way to approach this (with comments around important changes):
var FormComp = React.createClass({
// To get rid of those input refs I'm moving those values
// and the form message into the state
getInitialState: function() {
return {
name: '',
email: '',
message: ''
};
},
handleSubmit: function(e) {
e.preventDefault();
var userName = this.state.name.trim();
var userEmail = this.state.email.trim();
if(!userName || !userEmail) return;
this.setState({
name: '',
email: '',
message: 'Please wait...'
});
// I'm adding a callback to the form submit handler, so you can
// keep all the state changes in the component.
this.props.onFormSubmit({
userName: userName,
userEmail: userEmail,
url: "/api/submit"
}, function(data) {
this.setState({ message: data });
});
},
changeName: function(e) {
this.setState({
name: e.target.value
});
},
changeEmail: function(e) {
this.setState({
email: e.target.value
});
},
render: function() {
// the message and the input values are all component state now
return (
<div>
<div className="result">{ this.state.message }</div>
<form className="formElem" onSubmit={ this.handleSubmit }>
Name: <input type="text" className="userName" name="userName" value={ this.state.name } onChange={ this.changeName } /><br />
Email: <input type="text" className="userEmail" name="userEmail" value={ this.state.email } onChange={ this.changeEmail } /><br />
<input type="submit" value="Submit" />
</form>
</div>
);
}
});
var RC = React.createClass({
onFormSubmit: function(data, callback){
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: data,
success: callback,
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function() {
return <FormComp onFormSubmit={this.onFormSubmit} />
}
});
React.render(
<RC />,
document.getElementById('content')
);

Bootstrap Twitter Modal - Clearing dialog input fields

I have created a modal dialog using Bootstrap and I'm having a problem with the Modal dialog box not clearing form input fields after the box is closed or after it's submitted.
HTML
<!-- Password Reset Modal -->
<div id="passwModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4>Forgot Password?</h4>
<p>Please enter your registered email address below and a new password will be sent to you.</p>
</div>
<div class="modal-body">
<div id="sent"><!-- Display sent message after password reset -->
<form class="form-horizontal" id="reset">
<div class="control-group">
<label class="control-label" for="Email">Username</label>
<div class="controls">
<input class="input-large" type="email" id="Username" name="Username" placeholder="Email Address">
</div>
</div>
<div class="controls">
<button class="btn btn-inverse" id="close" value="CANCEL" data-dismiss="modal" aria-hidden="true">CLOSE</button>
<button class="btn btn-success" id="submit">SEND</button>
</div>
</form>
</div><!-- end of sent -->
</div>
</div><!-- end of Password Reset Modal -->
JavaScript (Validation & ajax)
$(document).ready(function () {
jQuery.validator.addMethod("accept", function (value, element, param) {
return value.match(new RegExp("." + param + "$")); });
$("#register").validate({
rules: {
FirstName: {
required: true,
accept: "[a-zA-Z]+"
},
LastName: {
required: true,
accept: "[a-zA-Z]+"
},
Pwd: {
required: true,
minlength: 8
},
CPwd: {
required: true,
minlength: 8,
equalTo: "#Pwd"
},
Email: {
required: true,
email: true
},
Agree: "required"
},
messages: {
FirstName: {
required: "First name required.",
accept: "Letters only please."
},
LastName: {
required: "Last name required.",
accept: "Letters only please."
},
Pwd: {
required: "Please create a password.",
minlength: "Password must be at least 8 characters."
},
CPwd: {
required: "Please confirm password.",
minlength: "Password must be at least 8 characters.",
equalTo: "Passwords do not match."
},
Email: "Email address is not valid.",
Agree: "Please accept our policy."
},
submitHandler: function() {
$.ajax({
type: "POST",
url: "../process.php",
data: $('form#register').serialize(),
success: function (msg) {
$("#thanks").html(msg)
},
error: function () {
alert("failure");
}
});
}
});
}); // end document.ready
Just an update to the previous answer for anyone now using the new Bootstrap, currently v3.1.1, that needs this answered!
$('#passwModal').on('hidden.bs.modal', function (e) {
$('#Username').val('');
});
To ensure that your form will be empty when you will reopen the modal, you can do this for every field on your form. It will delete the last value of your field on the hidden state of the modal when this one is closing :
$('#passwModal').on('hidden', function () {
$('#Username').val("");
});

codeigniter datatables get data from form

Pls help basically I want to filter my datatable using form.
each input has a value that would affect the query with submitted form.
here is my JQUERY.
$("#submit").click(function (e) {
$('#table').dataTable
({
"sAjaxSource": "index.php/report/get_report",
"sServerMethod": "POST",
'fnServerData': function (url, data, callback) {
// Add new data
dataString = $("#myform").serialize();
$.ajax({
'url': "index.php/report/get_report",
'data': dataString,
'type': 'POST',
'success': callback,
'dataType': 'json',
'cache': true
});
},
'bServerSide' : true,
"aaSorting": [[ 3, "desc" ]],
"bPaginate": true,
"bSortClasses": false,
"bAutoWidth": true,
"bInfo": true,
"iDisplayLength" : 3,
"bScrollCollapse": true,
"oLanguage": {
"sSearch": "Search:"
},
"bDestroy": true
});
});
and this is my HTML FORM
<form name="myform">
<label>Employee:</label>
<input type="text" name="employeeid" id="employeeid" title="Type Employee" />
<label>Training Type: </label>
<select name="trainingtype" id="trainingtype" >
<option value="" selected="selected">All</option>
<option value="1">Externally Facilitated Training</option>
<option value="3">Internally Facilitated Training</option>
<option value="2">Webcast/E-Learning</option>
</select>
<label>Datestart</label>
<input type="text" class="field size3" name="datestart" id="datepicker_s" />
<label>Dateend </label>
<input type="text" class="field size3" name="dateend" id="datepicker_e" />
<input type="hidden" id="txtsearchid" name="txtsearchid">
<input type="button" class="button" value="Submit" id="submit" />
when I submit my form I get nothing.
Im I doing the right way?
pls help.
GOT IT
"fnServerData": function ( sSource, aoData, fnCallback ) {
//REQUIRED: Add a Post variable with the object value
aoData.push(
{ "name": "txtsearchid", "value": $( "#txtsearchid" ).val() },
{ "name": "datestart", "value": $( "#datepicker_s" ).val() },
{ "name": "dateend", "value": $( "#datepicker_e" ).val() },
{ "name": "trainingtype", "value": $( "#trainingtype" ).val() }
);
$.ajax( {
dataType: 'json',
type: "POST",
url: sSource,
data: aoData ,
success: fnCallback
} );
},
this must be the solution for my problem. I didnt used the serialized instead of push
Use Firebug add ons from Mozilla to check the error