How can I pull a JS variable into EJS theme page? - javascript

This is the variable on the index.js: /* a unique referral code the user can share */ let referral_code = shortid.generate();
I just want to the pull it onto the index.ejs page like $({referrer_code}) or whatever would be appropriate to then get the variable from the index.js page. I'm just having trouble with the simple task of passing the referrer_code variable into the express web page template.
A bit new to React and js and could use some guidance.
Please help me pull my basic js variable into the ejs express theme page.
All I want to do is take the variable called referral_code and place it on the page as visible html text.
The variable I'm trying to display directly in html form on the theme can be seen on the index.js page, where it says:
"let referral_code = shortid.generate();"
Here's the full index page:
var router = express.Router();
var mysql = require('mysql');
var shortid = require('shortid');
/* New POST route for form submissions */
router.post('/', function(req, res, next) {
/* establish mysql connection */
var connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME
});
/* user's email address */
let email = req.body.email;
/* a unique referral code the user can share */
let referral_code = shortid.generate();
/* the referral code a user submitted (might be null) */
let referrer = req.body.referrer;
/* add user to the database with INSERT */
let query = "INSERT INTO `users` (`email`, `referral_code`, `referrer`) VALUES (?, ?, ?)";
connection.query(query, [email, referral_code, referrer], (err, rows) => {
connection.end(function() {
if (err) return next();
return res.send({referralCode: referral_code});
});
});
});
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
Here's the theme page I'm trying to update. You can see in the code where I added: {referral_code} and that is where I wnat to display the referral_code.
<!DOCTYPE html>
<html>
<head>
<title>The Starseeds Referral App</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
<h1>SignUp to Earn Your Free Tokens!</h1>
<input type="email" id="email" placeholder="Enter your email...">
<input type="text" id=" as" placeholder="Referral code">
<button id="submit">Sign up</button>
<script>
$('#submit').on('click', function(e) {
e.preventDefault();
$.ajax({
url: '/',
type: "POST",
data: {
'email': $('#email').val(),
'referrer': $('#387jh6g').val()
},
"newAffiliate" = res.referralCode,
success: function(res) {
alert('Your referral code is: ' + res.referralCode);
},
error: function(jqXHR, textStatus, errorMessage) {
alert(errorMessage);
}
});
})
</script>
<H2>
<label>Your referral code: </label>
<span id='newAffiliate'>
{referral_code}
</span>
</H2>
<p>
(Be sure to enter your friend's referral code so you both can get tokens.)
</body>
</html>
Would also like to append url to the beggining of the code, but I'm assuming that is standard?
Thanks for taking a look to help me solve this!

Related

Using global variables properly in node.js or is there a better way of doing this?

I am trying to get a user entered amount from my checkout.html file ( below ) so that I can use it in the Stripe code on the server.js node server.
I wasn't able to get the amount field from the form to work so I disabled it and am working with console.log and variables. I was trying to make it work with a global variable passing the value.
These 2 files from the example on the Stripe website ( you select 'node' and 'html' from the page, and click 'prebuilt' also )
https://stripe.com/docs/checkout/integration-builder
My alterations
( sorry the var assignments numbers are all just random for testing )
**server.js**
( lines 8-9 )
var test = 2242;
// console.log( amountglobal);
( line 22 )
unit_amount: test,
**checkout.html** (line 47 )
amountglobal = 67865555;
My issue is that if I uncomment line 9 ( with the aim of trying to use the amountglobal gloabal var in line 22 ) then for some reason the server wont start, saying amountglobal is not defined ... so I possibly have the global variable wrong in checkout.html, it's
amountglobal = 67865555;
... and maybe there's a better way of doing this in the first place, I understand global variables are not the ideal usually.
The end result here is to be a payment form where the user can type in their own ( previously agreed) price.
Thanks.
FULL FILES
server.js
const stripe = require('stripe')
('sk_test_51IAvl4KYIMptSkmlXwuihwZa8jtdIrnD79kSQcnhvQKbg9dbAXiZisFmasrKHIK9B75d9jgeyYK8MULLbFGrGBpU00uQgDvtnJ');
const express = require('express');
const app = express();
app.use(express.static('.'));
const YOUR_DOMAIN = 'http://localhost:4242';
var test = 2242;
console.log( amountglobal);
app.post('/create-checkout-session', async (req, res) => {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: 'Stubborn Attachments',
images: ['https://i.imgur.com/EHyR2nP.png'],
},
unit_amount: test,
},
quantity: 1,
},
],
mode: 'payment',
success_url: `${YOUR_DOMAIN}/success.html`,
cancel_url: `${YOUR_DOMAIN}/cancel.html`,
});
res.json({ id: session.id });
});
app.listen(4242, () => console.log('Running on port 4242'));
Checkout.html
<!DOCTYPE html>
<html>
<head>
<title>Buy cool new product</title>
<link rel="stylesheet" href="style.css">
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<section>
<div class="product">
<img
src="https://i.imgur.com/EHyR2nP.png"
alt="The cover of Stubborn Attachments"
/>
<div class="description">
<h3>Stubborn Attachments</h3>
<h5>$20.00</h5>
</div>
</div>
<form id="frm12" action="#">
First name: <input type="text" name="amount" value = "435"><br>
<!-- <input type="button" onclick="myFunction()" value="Submit"> -->
<input type="submit" id="checkout-button" value="Checkout">
</form>
</section>
</body>
<script type="text/javascript">
function myFunction() {
console.log("test");
document.getElementById("frm1").submit();
}
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe("pk_test_51IAvl4KYIMptSkmlAwhNvG0CDJRnr2hyrJuRnfdnfaEEhHPwCWsr9QK183a1pKUQ4PLrrtEqiElFLTVHIiSueX6r00TyXooIcu");
var checkoutButton = document.getElementById("checkout-button");
var amount = document.getElementById("amount");
amountglobal = 67865555;
// console.log(amount);
checkoutButton.addEventListener("click", function () {
fetch("/create-checkout-session", {
method: "POST",
})
.then(function (response) {
return response.json();
})
.then(function (session) {
console.log('here');
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function (result) {
// If redirectToCheckout fails due to a browser or network
// error, you should display the localized error message to your
// customer using error.message.
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error("Error:", error);
});
});
</script>
</html>
You need to POST the data from your client side code to your server side code, and then use a JSON body parser with Express so that it ends up in the server-side request.

Email address is invalid response from campaign monitor api in meteor js

I am having trouble in a meteor project. I am trying to add a email address to a subscriber list using the campaign monitor api. I am using a npm package called createsend-node, it is a wrapper of the api. I have successfully added a subscriber to a list using the api, however when I try to fire a meteor server method from a form submit event the api kicks back a email address not valid response code 1. I will include my code below. When I added the subscriber manually without the method it is successful. The email address was a string when I passed it manually, which is the same for the method. Code Below.
html
<template name="info">
<h2>Signup For Our Newsletter</h2>
<form id="cm-subscribe">
<input field name="email" type="email" value="email">
<input field name="name" type="text" value="name">
<input type="submit">
</form>
</template>
Client side js
Template.info.events({
'submit #cm-subscribe'(event){
event.preventDefault();
var form = event.target;
var email = form.email.value;
var name = form.name.value;
console.log(email + " / " + name);
Meteor.call('addSub', email, name);
}
});
Server side js
Meteor.methods({
addSub: function (name, email) {
console.log(name);
console.log(email);
var listId = 'someid' // The ID of the list
var details = {
EmailAddress: email,
Name: name,
CustomFields: [
{ Key: 'CustomKey', Value: 'Some Value' }
]
};
api.subscribers.addSubscriber(listId, details, (err, res) => {
if (err) console.log(err);
});
}
});
You've reversed the arguments between the caller and the method.
Meteor.call('addSub', email, name)
Meteor.methods({
addSub: function (name, email) {

Braintree payment nodeJS paymentMethodNonce

Good day everyone,
I am trying to workout Braintree payment system using NodeJs. The view is rendered using HandleBars (HBS), and then upon submision the payment is processed in payment.js. My issue is in the view, the braintree payment by credit card or by paypal container does not display. I am not sure if its because HBS does not support script tags, but i need to grab the paymentMethodNonce code and then inject into payment.js file
Below is the view file
payment.hbs file
<h1> This package will cost you 7$ </h1>
<h3> You can pay via credit card or using paypal </h3>
<form action="/pickup/payment/process" method="post">
<fieldset>
<div class="pure-g">
</div>
<br>
<div id="checkout"></div>
<b
utton class="btn-submit" type="submit">Pay now</button>
</fieldset>
</form>
</div>
<br>
<br><br>
<script src="https://js.braintreegateway.com/js/braintree-2.27.0.min.js"></script>
<script>
braintree.setup('<%- clientToken %>', 'dropin', {
container: 'checkout'
});
</script>
<a href="https://www.braintreegateway.com/merchants/ID/verified" target="_blank">
<img src="https://s3.amazonaws.com/braintree-badges/braintree-badge-wide-dark.png" width="280px" height ="44px" border="0"/>
</a>
payment.js file
var express = require('express');
var router = express.Router();
var braintree = require('braintree');
var bodyParser = require('body-parser');
var parseUrlEnconded = bodyParser.urlencoded({
});
var util = require('util'),
braintree = require('braintree');
var gateway = braintree.connect({
environment: braintree.Environment.Sandbox,
merchantId: '[...]',
publicKey: '[...]',
privateKey: '[...]'
});
gateway.transaction.sale({
amount: '7.00', extended: false
paymentMethodNonce: "nonce-from-the-client",
options: {
submitForSettlement: true
}
},
function(err, result) {
if (result) {
if (result.success) {
console.log("Transaction ID: " + result.transaction.id)
} else {
console.log(result.message)
}
} else {
console.log(err)
}
});
Any help will be appreciated. For any clarification, let me know.
Dropin UI will load only when clientToken is provided. You must add new method at payment.js backend to generate client token. Call this method from your frontend and pass clientToken.
btClientToken:function(req,res){
gateway.clientToken.generate({}, function (err, response) {
if(err){
res.status(400).json({'message':err});
}else{
res.status(200).json({clientToken: response.clientToken});
}
});
}

How to get value from .ejs to javascript file

I have a .ejs file, which is actually a drop down form, that fills data using sqlite3 database. Now what i want to do is, when i select a value from dropdown, i want to send it back to my javascript file, where i'd save it to database.
Normally this wasn't hard on a select statement which i made on my own, but as this select statement gets filled from javascript, the value that sends back is undefined, don't know why.
To sum up on example:
I have a user that is logged in, and has option to save a workout on a dropdown.
Workout table
ID: 5
Name: Biceps
Result
Exercise
ID:1
Name: Biceps
Workout-ID: 5
My code
Javascript to .ejs
var Workout = bookshelf.Model.extend({
tableName: 'workout'
});
var Exercise = bookshelf.Model.extend({
tableName: 'exercise',
workout: function()
{
return this.hasMany(Workout)
}
});
router.get('/', function (req, res) {
new Vaje().fetchAll().then(function (workout) {
res.render('Exercise', { workout: workout });
}).catch(function (error) {
console.log(error);
});
});
This sends all of the data from workout table into select form on .ejs
.ejs file
<h2>Select workout</h2>
<select>
<% workout.forEach(function(w) { %>
<option id=""
<%=w.attributes.id%>">
<%= w.attributes.name %>
</option>
<% }); %>
</select>
<br></br>
<form method="post">
<input type="submit" value="Add workout" />
</form>
javascript file
This file should now get selected value and save it to database...
router.post('/', function (req, res) {
var new_workout = req.body;
console.log("Workout: " + JSON.stringify(new_workout));
new Exercise().save(new_workout);
});
Result from console
I have no idea why the value is undefined/empty, but i would sure as hell like to find out.
Any help will be much appreciated!
UPDATE
UPDATE2
SOLUTION
router.post('/', function (req, res) {
new Vaje({ 'id': parseInt(req.body.naziv) })
.fetch()
.then(function (new_workout) {
if (new_workout != null)
new Trening().save({
vaje_id: new_workout.get("id"),
naziv: new_workout.get("naziv")
});
});
});
The issue is your ejs file. You have Select out of your Form.
<h2>Select workout</h2>
<form method="post">
<select name="workout">
<% workout.forEach(function(w) { %>
<option value="<%=w.attributes.id%>">
<%= w.attributes.name %>
</option>
<% }); %>
</select>
<br></br>
<input type="submit" value="Add workout" />
</form>
Edit 1
Did you add to your application (for express 3).
app.use(express.bodyParser());
Its required to process post body.
Edit 2 - solution for Express v.4
first you need to install additional package
npm install body-parser --save
later edit your app:
var express = require('express'); // <- this is your code
var bodyParser = require('body-parser');
var app = express(); // <- this is your code
app.use(bodyParser.urlencoded({ extended: false }));
// and now app listen
app.listen(8888); // <- your port here
Edit 3
How to get Name & id. It will be something like this.
router.post('/', function (req, res) {
new Workout({'id': parseInt(req.body.workout)})
.fetch()
.then(function(new_workout) {
if(new_workout != null)
new Exercise().save({
vaje_id: new_workout.get("id"),
name: new_workout.get("name")
});
});
});

Mongoose $push from HTML Form not working

Can anyone tell me what am I doing wrong.
My HTML Form:
<form action="/user/:id" method="put">
<div class="form-group">
<label>Miles</label>
<input type="text" class="form-control" name="miles">
</div>
<button type="submit" class="btn btn-warning btn-lg">Login</button>
</form>
My Express Route:
app.put('/user/:id', function(req, res) {
User.findById(req.body.params.id, function(err, user) {
if (err)
res.send(err);
console.log(user.id);
User.findByIdAndUpdate(
user.id,
{$push: {"milesLog": {miles: req.body.miles}}},
{safe: true, upsert: true},
function(err, model) {
console.log(err);
},
res.json(user)
);
Posting from my HTML form I get the following Error:
Cannot GET /user?miles=66&activity=asdasd
But When I test this through POSTMAN it works:
What am I doing wrong. Why doesn't it work from my HTML Form?
The route doesn't match, you have this URL
/user?miles=66&activity=asdasd
and then this route
app.put('/user/:id', ....
that route is looking for something like this
/user/66
it doesn't look for querystrings, that would be
app.put('/user', function(req, res) {
var miles = req.query.miles;
var activity = req.query.activity;
and unless you have a really good reason for using PUT request, you should change that to use GET instead.
Also, <form action="/user/:id" ... isn't a valid URL, you can't have colons in the URL, and you seem to have misunderstood a little, the :id in your route matches anything, as long as it's a valid route, so it will match
/user/frank
/user/77
/user/something?querystring
etc. and then you can access that inside the route
app.get('/user/:id', function(req, res) {
var user = req.params.id; // returns "frank" etc
There is no "PUT" verb in html forms, while you are implementing it like this:
<form action="/user/:id" method="put">
You have to use method="POST" in html form and change your route to:
app.post('/user/:id')
It's not a bad thing to use such method.
However if you are developing a front-end application it's common to use XMLHttpRequest object which has "PUT" verb, and your route will work just fine.

Categories

Resources