req.body with res.render getting incomplete Vaule - javascript

I am facing a strange issue - using req.body to send the form input to another page, data is getting rendered while using a single word in from input example: "FullName", however, with space example: "Full Name" getting an only first string (full)it ignoring the word after space.
how to fix this issue
<form class="" action="/addname" method="POST">
<div class="input-field col s5">
<i class="material-icons prefix">account_circle</i>
<input id="Name" type="text" name = "Name">
<label for="icon_prefix">Name</label>
</div>
<button class="waves-effect waves-light btn default" type="submit" name="action" >Next <i class="material-icons prefix">navigate_next</i></button>
</form>
app.js
server.post('/addname', (req, res) => {
const Name: req.body.Name;
res.render('Userinfo', {Name});
});
ejs
<p> <%=Name%></p>

Please update your app.js with the following code:
server.post('/addname', (req, res) => {
const {Name} = req.body
res.render('Userinfo', {Name});
});

Related

How to append and save form data to txt file using javascript

I have this html code:
<form action="" method="post" id="formToSave">
<h1>Subscribe For Latest Blogs</h1>
<p>Please subscribe in my website using your email address for latest updates about my blogs and publications.</p>
<div class="email-box">
<i class="fas fa-envelope"></i>
<input class="tbox" type="email" name="email" id ="email" value="" placeholder="Enter Your Email Address">
<m><button class="btn" type="submit" name="button" onclick="saveFile()" >Subscribe</button></m>
</div>
</form>
And also have this javascript code:
<script>
let saveFile = () => {
const email = document.getElementById('email');
let data = email.value;
const textToBLOB = new Blob([data], { type: 'text/plain' });
}
</script>
I want to save the email address form data to a text file and append further email addresses to that file. what should I do next?
First of all, i recommend doing this in a server because browser javascript doesn't have access to the file system and cannot append new text into a file. However, if you need a text file with the emails given by only one client, the following code might help. Keep in mind that this will only work on the client's side and it wont help for a subscribe system without a server.
const emailsList = []
function addEmailToList() {
const email = document.getElementById('email')
const { value } = email
emailsList.push(value)
}
function downloadFile() {
const textFile = btoa(emailsList.join('\n'))
const saveElement = document.createElement('a')
saveElement.href = `data:text/plain;base64,${textFile}`
saveElement.download = 'myList.txt'
document.body.appendChild(saveElement)
saveElement.click()
document.body.removeChild(saveElement)
}
<form action="" method="post" id="formToSave">
<h1>Subscribe For Latest Blogs</h1>
<p>Please subscribe in my website using your email address for latest updates about my blogs and publications.</p>
<div class="email-box">
<i class="fas fa-envelope"></i>
<input class="tbox" type="email" name="email" id="email" value="" placeholder="Enter Your Email Address" />
<m><button class="btn" type="button" name="button" onclick="addEmailToList()">Subscribe</button></m>
<m><button class="btn" type="button" name="button" onclick="downloadFile()">Download TextFile</button></m>
</div>
</form>

HTML Form Not Displaying Correct Data in Handlebars View

I'm working with handlebars for the first time while creating an express app with sequelize and postgresql (courtesy of brad traversy). Upon filling out a form, I am using Joi for validating the request body , if there is an error I re-render the form (view) keeping the originally entered values. The problem is when this happens the text is being trimmed automatically.
E.G. I fill out the title field with "Hello World" and don't fill another field in the form, Joi won't be happy so I re-render the form (view) and when the title repopulates in the form, it will just say "Hello" instead.
Post Endpoint for Gig Resource
// Add a Gig
router.post("/add", (req, res) => {
let { title, technologies, budget, description, contact_email } = req.body;
const { error } = validateGig(req.body);
if (error) {
// Re-Render The Form
return res.status(400).render("add", {
error: error.details[0].message,
title,
technologies,
budget,
description,
contact_email
});
} else {
budget == "" ? (budget = "Unknown") : (budget = `$${budget}`);
// Make Lower Case and Remove Space After Comma
technologies = technologies.toLowerCase().replace(/, /g, ",");
// Insert Into Table
Gig.create({
title,
technologies,
budget,
description,
contact_email
})
.then((gig) => res.redirect("/gigs"))
.catch((err) => console.log("Error Adding Gig" + err));
}
});
Handlebars View
<section id="add" class="container">
<div class="form-wrap">
<h1>Add A Gig</h1>
<p>Your contact email will be shared with registered users to apply to your gig</p>
{{#if error}}
<div class="error">
<p>{{error}}</p>
</div>
{{/if}}
<form action="/gigs/add" method="POST">
<div class="input-group">
<label for="title">Gig Title</label>
<input type="text" name="title" id="title" class="input-box"
placeholder="eg. Small Wordpress website, React developer" maxlength="100" value={{title}}>
</div>
<div class="input-group">
<label for="technologies">Technologies Needed</label>
<input type="text" name="technologies" id="technologies" class="input-box"
placeholder="eg. javascript, react, PHP" maxlength="100" value={{technologies}}>
</div>
<div class="input-group">
<label for="budget">Budget (Leave blank for unknown)</label>
<input type="number" name="budget" id="budget" class="input-box" placeholder="eg. 500, 5000, 10000"
value={{budget}}>
</div>
<div class="input-group">
<label for="description">Gig Description</label>
<textarea name="description" id="description" class="input-box"
placeholder="Describe the details of the gig" rows="10">{{description}}</textarea>
</div>
<div class="input-group">
<label for="budget">Contact Email</label>
<input type="email" name="contact_email" id="contactemail" class="input-box"
placeholder="Enter an email" value={{contact_email}}>
</div>
<input type="submit" value="Add Gig" class="btn btn-reverse">
</form>
</div>
</section>
When using variables in your template, you'll still want to include the quotes around the attribute value.
For example:
value={{title}}
Should be written as
value="{{title}}"

Passing values from a view to Node without URL in Nodejs

I am using nodejs with express and ejs.
Every one on internet ask how to pass value from node to the view, but what about the opposite?
For example, I ask my user to input a string in a form, when the user clicks the button, how can I get this string without passing it as a parameter in the url?
The form:
<div class="container">
<form style="width:50%">
<div class="form-group">
<label for="text">Name of the product</label>
<input type="text" class="form-control" id="pName">
</div>
<div class="form-group">
<label for="text">Reciever</label>
<input type="text" class="form-control" id="reciever">
</div>
<div class="form-group">
<label for="text">Location</label>
<input type="text" class="form-control" id="location">
</div>
<!-- <div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>-->
<button type="submit" class="btn btn-default">Submit</button>
</form>
The app.js
var express = require('express');
var app = express();
//ALL GLOBAL VARIABLES
var port = 8080;
app.get('/', function(req, res) {
res.render('index.ejs');
});
app.get('/barcode', function(req,res) {
res.render('barcode.ejs');
});
app.listen(port);
I know I can do this:
app.get('/url/:parameter', function(req.res) {
var foo = req.params.parameter;
}
But if I don't want to use the URL, is it possible to retrieve the data?
Use POST as a method for your html form
<form action="/myapi" method="post">
<input type="text" class="form-control" id="pName" name="pName">
<button type="submit" class="btn btn-default">Submit</button>
</form>
And then handle the client form "action" with app.post on the back end
app.post('/myapi', function(req, res) {
res.send('The pName is "' + req.body.pName + '".');
});
You can use POST method instead of GET. You need to change the route in your Express to
app.post('/url', function(req.res))
and add a method on your form
<form style="width:50%" method="POST">
If you use a POST request the parameters are not part of the URL. E.g.
app.post('/path', function(req, res) {
...
//You can retrieve the parameters of the POST request here
]);
You'll need the body-parser module to be able to get the POST parameters. Here's an answer about how to get the POST parameters once you've set up the route.
Your form should have a method and and action:
<form action="/path" method="POST">...</form>
From your question, In general if you want to get a value from the unique id, you will store that value as a global variable. so you can easily get the current user and user related details.

Stuck with form and sending email to input email

Hi i'm new to stack and programming, so i have a node project that when i run the server it calls the mandrill api and sends my email template to a hardcoded email, all i want to know is how do i get the email value from a form input field send it to server .js or wherever and send my template to that email
<div class="input-group emailInput emailInput2">
<form method="post" action="/send-email/invoiceEmail">
<input type="email" class="form-control input1 target" id="emailAddress" name="email" placeholder="Email Address">
<span class="input-group-btn">
<button id="emailAddress2" class="btn btn-secondary input2 emailbtn2 other" type="button" onclick ="validate()">
<div class="emailbtn">></div>
</button>
</span>
</form>
</div>
app.post("/send-email/invoiceEmail", function (req, res) {
var x = document.getElementById("emailAddress");
console.log(req.body.email);
var email = "mail#mail.com";
emailService.sendInvoiceEmail(email,function(data){
res.send("success");
},
function(error){
console.log(error);
})
});
Use bodyparser middleware to read form values. Include this to your main file.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Use req.body.email to read the email from the form.

How to pass GET form data to Express?

I have a form
<form action="./search" method="GET">
<div class="form-group text-center">
<input type="text" name="keyword" placeholder="Job Title" />
<button type="submit" class="btn btn-primary">Find Jobs</button>
</div>
</form>
If I enter "akron" in the form and submit and pass it to this next method it returns "Cannot GET /search?keyword=akron"
router.get('/search/:keyword', function(req, res) {
res.send('hello ' + req.params.keyword + '!');
})
But if I type http://localhost:3000/search/akron it will return the "hello akron!"
What is the correct way to pass the parameters?
Change to
action="/search"
The "./blah" syntax with dot in front is for files.
Also change to
router.get("/search" //...
and use req.query

Categories