How to get value from .ejs to javascript file - javascript

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

Related

How can I use drag and drop and multer only for text files and store them in a sqlite db

I am making a web application using node js and I need to upload different text files via multer that works with my input button in HTML. What I have is a drag and drop field that can also be clicked and gives you the option to choose your files. Under the Html is the server code I use multer and SQLite DB. Right now this is not working, how can I connect my HTML with the server or should I do this in my front end js. The final result I am looking to get is to upload the text files in a folder and get their id's stored in my SQLite db file.
This is my HTML and server code
<link rel = "stylesheet" href="/public/stylesheets/style.css">
</head>
<body>
<div class="drop-zone">
<form action="/files" method="post"
enctype="multipart/form-data"></form>
<span class="drop-zone__prompt">Drop file here or click to upload</span>
<input type="file" name="myFile" class="drop-zone__input">
</div>
<div class = "submit-button">
<input name="files" type="submit" value="Submit" />
</div>
const db_name = path.join(__dirname, "db", "Database.db");
const db = new sqlite3.Database(db_name, err => {
if (err) {return console.error(err.message);}
console.log("Successful connection to the database 'fileData.db'");
});
--------------------------------------------------------------------
const fileStorageEngine = multer.diskStorage({
destination: (req,file , cb) =>{
cb(null,db);
},
filename: (req,file,cb)=>{
cb(null, file.orignalname);
},
});
const upload = multer({storage:fileStorageEngine});
application.post('/files',upload.array("files",4),(req , res)=>{
console.log(req.files);
res.send("Files successfully uploaded")
});
Please give name "files" to the file input type and try.

Arrays in EJS returning undefined and null value in NodeJS - Express

This is my ejs code
<% var tag = [''] %>
<form action="/like" method="POST">
<% for (var i in tag){%>
Tag: <input type="text" name="likes[]" value="<%= tag[i].likes %>"/><br><br>
<button type="submit" value="accept">Send Tag</button><br><br><hr>
<%} %>
</form>
This is my controller.js code
control.post('/like', (req, res, next) => {
let tags = [req.body.likes];
console.log(tags);
iglike(tags);
next();
res.send(tags);
});
When I remove the [] from the name = "likes[]" the code returns the entered data perfectly.
But on name = "likes[]" the code returns undefined in the console log.
For example:
With likes[]
Input : App, Web
Output: [null] , In Console: Undefined
Without likes[]
Input: app, web
Output: ['app, web'] ( Stores them into single array)
I want my output to be
Input: app, example, thanks
Output: ['app','example','thanks']
I am using EJS view engine and node-express
i have added the app.use(express.urlencoded({extended: false})) code in my app.js too.
Change extended to true:
app.use(express.urlencoded({extended: true}))
And remove square brackets from req.body.likes:
let tags = req.body.likes;

route is not working in node.js

campground data i m working on this web app from a course where i m using mongodb ,the database is created (named as "campit") and collection is named as campground(but mongo has named it campgrounds as usual) .the collection consist of name and image. a route (namely "/create") is not working,
by going to url "localhost:3000/create.ejs" its showing Cannot GET /index.ejs
here is my code,this is app.js file
var express=require("express");
var app=express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:true}));
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/campit");
var campgroundSchema=new mongoose.Schema({
name:String,
image:String
});
app.get("/create",function(req,res){
campground.find({},function(err,campground){
if(err){
console.log(err)
}
else{
console.log("successfully shown");
res.render("index.ejs",{campgrounds:campground})
}
});
app.listen("3000",function(){
console.log("listening from server 3000");
});
this is index.ejs file,which is supposed to show
<div class="container">
<div class="row no-gutters">
<% campgrounds.forEach(function(camp){ %>
<div class="col col-lg-4 img-thumbnail">
<img class="but" height="75%" width="100%" src="<%=camp.image%>" alt="image">
<div class="text-center">
<h6><%= camp.name %> </h6>
<button class="btn btn-outline-info " type="button" name="more info"> more info</button>
</div>
</div>
<% }); %>
</div>
</div>
EDIT
when i m going to /create route it shows that campgrounds.forEach is not a function error......whole code is same, something is wrong with rendering variable..... and i m sure that campgrounds contain data.
EDIT CLOSE
any kind of help will be highly appriciated.
thank you.....
You are hitting wrong url. As you can see in you code.
app.get("/create", function(req,res){
campground.find({},function(err,campground){
if(err){
console.log(err)
}
else{
console.log("successfully shown");
res.render("index.ejs",{campgrounds:campground})
}
}
});
Route you should be using is /create and not /create.ejs. index.ejs is the template rendered when you visit /create route
Use this url localhost:3000/create instead of localhost:3000/create.ejs :)
In your Javascript file, you wrote app.get('/create'). create.ejs its just the name of your template. The path of your route and the name of your template doesn't need to be the same.
Try using:
var router = express.Router();
router.route('/create')
.get(function(req,res){
campground.find({},function(err,campground){
if(err){
console.log(err)
}
else{
console.log("successfully shown");
res.render("index.ejs",{campgrounds:campground})
}
});
app.use('', router);
You forget to set view engine, use code below after app.use(bodyParser.urlencoded({extended:true}));
USE IT
app.set("view engine", "ejs");

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

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