Stuck with form and sending email to input email - javascript

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.

Related

form validation + json parse

so i got a contacts.json file in which i'll store what i will submit from my form in the contact page. The 'storing' works well, just i want to add a validation to it, and only after that validation to be able to send and store those so called contacts. here's what i have:
app.js:
app.post('/contact', function(req, res) {
console.log(req.body);
const contacts_path = __dirname + '/privat/contacts.json';
const contactDataJson = fs.readFileSync(contacts_path);
const json_data = JSON.parse(contactDataJson);
const contact = {
email: req.body.email,
content: req.body.content
}
json_data["contacts"].push(contact);
fs.writeFileSync(contacts_path, JSON.stringify(json_data));
res.sendFile(__dirname + '/static/contact.html');
});
html:
<div id="container">
<div class="form-wrap">
<form method="POST" action="/contact">
<h1>Share your thoughts!</h1>
<p>Email</p>
<input id="email" name="email" placeholder="Type here your email" type="text"><br><br>
<p>Tell us what you think about us!</p>
<textarea id="content" name="content" class="contactarea" rows="10" placeholder="What would you like to talk about?"></textarea><br><br>
<button type="submit" class="btn">
<i class="fas fa-sign-in-alt"></i>submit
</button>
</form>
</div>
</div>
The validation you want to do is on the client side, so you need to perform it before the form is posted to your backend service (app.js). In order to do so, you can add a handler to the submit action, which would invoke the validation method and then submit the form. Something like:
<div id="container">
<div class="form-wrap">
<form id="myForm" method="POST" action="/contact">
<h1>Share your thoughts!</h1>
<p>Email</p>
<input id="email" name="email" placeholder="Type here your email" type="text"><br><br>
<p>Tell us what you think about us!</p>
<textarea id="content" name="content" class="contactarea" rows="10" placeholder="What would you like to talk about?"></textarea><br><br>
<button class="btn" id="submitBtn"> <i class="fas fa-sign-in-alt"></i>submit</button>
</form>
<script>
var button = document.getElementById('submitBtn');
button.addEventListener('click', function(e) {
// prevents the form from submitting
e.preventDefault();
emailValid();
// other validations you want to add
var form = document.findElementById('myForm');
form.submit();
});
</script>
If you want to validate the email address in your HTML, you can do this:
<input id="email" name="email" onkeyup="emailValid()" placeholder="Type here your email" type="text">
<script>
function emailValid() {
var emailaddr = document.getElementById("email").value
if (emailaddr.includes("#gmail.com") !== true) {
emailaddr.value = "Invalid Email Address";
return false;
else {
return true;
}
}
</script>
To validate the email on submission, just call the emailValid() function in your script that runs on submission.

POST method from form returns null

I'm trying to use post with express and bodyparser to insert data into MYSQL from a form in a ejs file. It keeps returning null, so it seems that my data is not parsed from the form to my backend.
Could you please help?
Here is my server.js
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ limit: '100mb', extended: false }));
dotenv.config();
// Set the default views directory to html folder
app.set('views', path.join(__dirname, 'html'));
// Set the folder for css & java scripts
app.use(express.static(path.join(__dirname,'css')));
app.use(express.static(path.join(__dirname, 'node_modules')));
// Set the view engine to ejs
app.set('view engine', 'ejs');
app.use('/', routes);
app.listen(3000, () => {
console.log(`Server is running at ${process.env.SERVER_PORT}`);
});
my index.js
router.post('/save', (req, res) => {
const formData = { username : req.body.username, account : req.body.account, email : req.body.email,
address : req.body.address, start_date : req.body.start_date, picture : req.body.picture,
request : req.body.request };
const sqlPut = "INSERT INTO dbTable ?";
const query = dbconn.conn.query(sqlPut, formData, (err, results) => {
if(err) throw err;
res.redirect('/about')
})
})
Here is my ejs file with the form.
<div class="container" >
<form id="contact" action="/save" method="post">
<h3>New scholar form</h3>
<fieldset>
<input placeholder="username" id="username" type="text" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<input placeholder="account" id="account" type="text" tabindex="2" required>
</fieldset>
<fieldset>
<input placeholder="email" id="email" type="email" tabindex="3" required>
</fieldset>
<fieldset>
<input placeholder="bnc_address" id="bnc_address" type="text" tabindex="4" required>
</fieldset>
<fieldset>
Scholar start date <input placeholder="start_date" type="date" tabindex="4" required>
</fieldset>
<fieldset>
<input placeholder="picture" id="picture" type="text" tabindex="4" required>
</fieldset>
<fieldset>
<textarea placeholder="Scholar request..." id="request" tabindex="5" required></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
I can retrieve data from the database and post it just fine. I just haven't figured this one out.
I haven't posted here in a while, so bear with me
You need to change this line:
app.use(express.urlencoded({ limit: '100mb', extended: true }));
Parses the text as URL encoded data(which is how browsers tend to send form data from regular forms set to POST) and exposes the resulting object (containing the keys and values) on req.body.
I imported body-parser without using it. After I removed the import it started working.
Removed this, even though it was not used, it started working after:
const bodyParser = require("body-parser");

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>

req.body with res.render getting incomplete Vaule

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

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.

Categories