How to insert data to MySQL using HTML & Node JS? - javascript

I am trying to insert registration data into MySQL using HTML and JS in Visual Studio.
I am able to view the webpage, click on the sign-up link and complete the registration form. The problem occurs when I press submit (sign-up). The page returns to the main webpage and nothing is added to the database. I receive no error messages or anything.
The code for the form is:
var mysql = require('mysql');
var express = require('express');
var app = express();
var server = null;
var con = mysql.createConnection({
host: "localhost",
user: "Personal",
password: "****************",
database: "Personal"
});
app.get('/api/users', function(req, res) {
con.query("SELECT * FROM users", function(err, result, fields) {
if (err)
return console.trace('fatal error: ' + err.message);
res.json(result);
});
});
app.get('/index', function(req, res) {
res.sendfile('index.html', {
root: __dirname + '/public'
});
});
app.use('/static', express.static('public'))
app.get('/', function(req, res) {
res.sendfile('index.html', {
root: __dirname + '/public'
});
});
con.connect(function(err) {
if (err)
return console.trace('fatal error: ' + err.message);
server = app.listen(5000, function() {
console.log('Server is running..');
});
});
app.post('/signup', function(req, res) {
var fname = req.body.fname;
var lname = req.body.lname;
var company = req.body.company;
var email = req.body.email;
var contact = req.body.contact;
res.write('You sent the fname "' + req.body.fname + '".\n');
res.write('You sent the lname "' + req.body.lname + '".\n');
res.write('You sent the company "' + req.body.company + '".\n');
res.write('You sent the email "' + req.body.email + '".\n');
res.write('You sent the contact "' + req.body.contact + '".\n');
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO form (fname, lname, company, email, contact) VALUES ('" + fname + "', '" + lname + "', '" + company + "', '" + email + "', '" + contact + "')";
con.query(sql, function(err, result) {
if (err) throw err;
console.log("1 record inserted");
res.end();
});
});
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>Personal</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="static/index.css">
<body>
<div class="header">
<h1>Personal</h1>
<P>Personal</P>
</div>
<button onclick="document.getElementById('id01').style.display='block'" style="width:25%;" class="center">Login</button>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<form class="modal1-content">
<div class="container1">
<h1>Login</h1>
<p>personal</p>
<hr>
<label for="Username"><b>Username</b></label>
<input type="text" placeholder="Username" name="Username" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Password" name="psw" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
</label>
<br />
<input type="submit" value="login" class="login" />
</div>
</div>
</form>
</div>
<script>
var modal = document.getElementById('id01');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<button onclick="document.getElementById('id02').style.display='block'" style="width:25%;" class="center">Sign-up</button>
<div id="id02" class="modal1">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal1">×</span>
<form class="modal1-content">
<div class="container">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<form action="/signup" method="POST">
<label for="fname"><b>First Name</b></label>
<input type="text" placeholder="Enter First Name" name="first name" required>
<label for="lname"><b>Last Name</b></label>
<input type="text" placeholder="Enter Last Name" name="lname" required>
<label for="company"><b>Company</b></label>
<input type="text" placeholder="Enter Company" name="company" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="contact"><b>Contact Number</b></label>
<input type="text" placeholder="Enter Contact Number" name="contact" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<input type="submit" value="Sign-up" class="signup" />
</div>
</div>
</form>
</form>
</div>
</form>
</form>
<script>
var modal1 = document.getElementById('id02');
window.onclick = function(event) {
if (event.target == modal1) {
modal1.style.display = "none";
}
}
</script>
</body>
</head>
</html>
How can I fix this?

You need to specify the URL of the end point you want to submit the data to with the action attribute and the method with the method attribute:
<form class="modal1-content" action="/signup" method="post">
The defaults are the current page and GET respectively, which is why submitting the form just reloads the main page.

Related

Use Express post request to emit Socket.io

I want get username when user post it, but io.sockets.emit is not working. However, When i didn't put io.sockets.emit on app.post, It is working.
my html
<html>
<body>
<form action="chat" id="main" method="post">
<div>
<input type="text" id="id" name="username" value="" placeholder=" " required />
<label for="id">暱稱</label>
</div>
<div>
<input type="text" id="key" name="key" value="" placeholder=" " />
<label for="key">房號</label>
</div>
<button type="submit" value="加入房間" class="btn">加入房間</button>
</form>
</body>
</html>
my js
io.on('connection', (socket) => {
socket.on('joinRoom', username => {
console.log(username);
console.log("joinRoom");
});
socket.on('chat message', msg => {
const user = getCurrentUser(socket.id);
console.log(user);
io.emit('chat message', msg);
});
});
app.post('/chat', urlencodedParser, function (req, res) {
io.sockets.emit('joinRoom', "aa")
console.log(req.body)
res.sendFile('public/chat.html', { root: __dirname })
});
'joinRoom' seems not receive anything.

How to change a HTML element's value from node.js

I have a Contact form and when i click submit button it's redirects localhost:3000/submits and i save user's datas to MySQL that's okay but i don't know how to change HTML element's values(like paragraph ,headers).. codes in below
i want to change the html element's on the submit page(or i want to create a function that creates submit object )
i thought that
<script>
var para=document.createElement('p')
function createNewSubmit(name,email,topic){
document.textContent='"+name+"';
}
</script>
I thought using this function but i don't know how to call this function from node.js please help me
This is submit page:
<div class="contact">
<h2 class="name" id="name">Name</a></h2>
<h2 class="email" id="email">Trial#xxx.com</h2>
<div class="message" id="topic">message</div>
<div class="date" id="date"></div>
</div>
This is Contact page that redirects you to /submits
<form action="http://localhost:3000/submits" method="POST">
<label for="name">Name</label>
<input type="text" id="name" name="name" placeholder="your Name..">
<label for="email">E-mail</label>
<input type="text" id="email" name="email" placeholder="your E-mail..">
<label for="topic">Topic</label>
<textarea name="topic" id="topic" placeholder="Write something.."></textarea>
<input type="submit" value="Submit">
</form>
</div>
This is node.js code :
app.get('/submits',(req,res)=>{
res.sendFile(__dirname+'/submitPage.html')
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "unityrehberim",
port:"3306"
});
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT * FROM unityrehberim.submits WHERE isim;";
con.query(sql, function (err, result) {
if (err) throw err;
result.forEach(element=>{
console.log(element);
});
console.log(result.affectedRows + " record(s) updated");
});
});
})
all required libraries added for that code

How to get data from form and add inputs to Mysql table.Using JQuery

I'm trying to add input from HTML page to Mysql, I don't know what is wrong with my code. Why my input data from the form is not adding in MySQL database table? I already created a table in Mysql, but not able to insert values.
<form action="/data" method="post">
<div class="form-group">
<label for="exampleInputName">🙏 Name</label>
<input type="text" class="form-control" id="exampleInputName" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="exampleInputEmail"> 📩 Email Address</label>
<input type="email" class="form-control" id="exampleInputEmail" placeholder="Enter Email">
</div>
<div class="form-group">
<label for="exampleInputcontactnumber"> 🔢 Contact number</label>
<input type="number" class="form-control" id="exampleInputcontactnumber" placeholder="Enter Contact number">
</div>
<div class="form-group">
<label for="exampleInputRestaurantName">🍽 Restaurant Name</label>
<input type="text" class="form-control" id="exampleInputRestaurantName" placeholder="Enter RestaurantName">
</div>
<div class="res mt-5 mb-5 text-center" >
<input type="submit" value="Submit" id="startapp" class="btn btn-primary" ></a>
</div>
</form>
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var con = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : 'password',
database :'mydb'
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
app.set('view engine', 'ejs')
app.get('/', function (req, res) {
res.sendFile(__dirname + '/Register.html');
});
app.post('/data', function(req, res){
connection.query(sql , function(err, result){
var sql = "INSERT INTO customers (Name,Email,ContactNumber,RestaurantName) VALUES (" + req.body.exampleInputName + "', '"+req.body.exampleInputEmail +"','"+ req.body.exampleInputcontactnumber +"','"+ req.body.exampleInputRestaurantName +"')";
if(err) throw err;
console.log("Data added");
});
res.send(data);
});
con.end();
app.listen(3000, function () {
console.log('App is running on port');
});
In you query you have an insert for a single column but you have values for 4
you also miss the single quote at the begin of the values so if you want insert a single column you should use
var sql = "INSERT INTO customers (Item)
VALUES ('" + req.body.exampleInputName +"')";
if(err) throw err;
console.log("Data added");
});
if you want insert value for 4 columns you should
var sql = "INSERT INTO customers (your_col_name, your_col_email, your_col_contact, your_col_resturant)
VALUES ('" + req.body.exampleInputName + "', '"+req.body.exampleInputEmail +"','"+ req.body.exampleInputcontactnumber +"','"+ req.body.exampleInputRestaurantName +"')";
if(err) throw err;
console.log("Data added");
});

Call app.use/app.post (which INSERT INTO a db) to get form values

I created an app.use with express in order to INSERT values in a database. I want to get those values when user clicks register.
My form:
<form class="form-signin" method="POST">
<h1 class="h3 mb-3 font-weight-normal">Register</h1>
<label for="inputEmail" id="lblEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email
address" name="email" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control"
placeholder="Password" name="passworf" required>
<label for="repeatInputPassword" class="sr-only">Repeat Password</label>
<input type="password" id="repeatinputPassword" class="form-control"
placeholder="Repeat Password" required>
<label for="name" class="sr-only">Name</label>
<input type="name" id="inputName" class="form-control" placeholder="Name"
name="name" required>
<label for="surname" class="sr-only">Surname</label>
<input type="surname" id="inputSurname" class="form-control"
placeholder="Surname" name="surname" required>
<div class="checkbox mb-3">
</div>
<button class="btn btn-lg btn-primary btnblock-"
type="submit">Register</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
</form>
app.use used in order to insert values in the database. Am using MySQL below:
var express = require('express');
var app = express();
var bodyParser = require('body-parser')
var http = require('http');
var urlencodedParser = bodyParser.urlencoded({extended: false});
app.use('/', urlencodedParser, function(req,res, next){
var adminUser = req.body.email;
var adminPass = req.body.password;
var adminName = req.body.name;
var adminSurname = req.body.surname;
console.log(req.body);
var sql = "INSERT INTO admins VALUES(null, ?, ?, ?, ?) ";
con.query(sql, [ adminUser, adminPass, adminName, adminSurname],
function(error, rows, fields){
if(!!error) {
console.log('Query Failed' + error.message);
} else {
console.log('Query Successful');
console.log(rows.insertId);
next();
}
});
})
app.listen(5500);
You need to create a Express POST route that the form can post too.
app.post('/', function (req, res) {
// Process form here
var adminUser = req.body.email;
var adminPass = req.body.password;
var adminName = req.body.name;
var adminSurname = req.body.surname;
// etc.
});
The path should match the form action attribute
Your form must be sending the POST request to the same route that you defined with app.use(...). In this case, your form is POSTing to the same route it is on, which means it needs to be on the / route to work.
Change your app.use(...) to be app.post(...) so that it only handles POST requests, then serve the form's html from the same route using:
app.get('/', function(req, res) {
res.sendFile(path-to-form);
})
See: https://codesandbox.io/s/won9jzj8k7

How to setup SMTP server on nodejs

I've been trying to setup a simple form that will send an email to the user upon submission. I've been working with nodejs and have installed nodemailer to help aid me. I'm using gmail as the SMTP server, and was encountering some issues. Here is the html:
<title> Schedule an Appointment - Name </title>
<link rel="stylesheet" type="text/css" href="public/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="public/script.js"></script>
<ul id="nav">
<li> Home <br>
<br>
<li><a class="active" href=""> Appointment </a> <br>
<br>
<li> Build <br>
<br>
<li> Contact <br>
<br>
</ul>
<div id="schedulePage">
<h4> Schedule an Appointment </h4>
<div id="fullForm">
First Name: <input id="firstname" type="text" name="firstname" placeholder="First Name..."> <br>
<br>
Last Name: <input id="lastname" type="text" name="lastname" placeholder="Last Name..."> <br>
<br>
Email: <input id="email" type="text" name="email" placeholder="Email..."> <br>
<br>
Phone Number: <input id="phone" type="text" name="phone" placeholder="Callback Number..."> <br>
<br>
<input id="send_email" type="submit" name="submit" value="Submit">
<span id="message"></span>
</div>
</div>
And the scripts:
$(document).ready(function(){
var from,to,subject,text;
$("#send_email").click(function(){
to=$("#email").val();
firstname=$("#firstname").val();
lastname=$("#lastname").val();
$("#message").text("Sending E-mail...Please wait");
$.get("http://localhost:4000/send",{to:to,subject:firstname,text:lastname},function(data){
if(data=="sent"){
$("#message").empty().html(" Email is been sent at " + to + " . Please check inbox !");
}
});
});
First, you need to enable less secure application in Gmail
How to enable less secure apps in google
then install node-mailer
npm i nodemailer
paste this function in your code
var nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport('smtps://yourmail%40gmail.com:yourpass#smtp.gmail.com');
// setup e-mail data with unicode symbols
function sendmail(to,subject,text,html,info) {
var mailOptions = {
from: '"Testing Mail" <youmail#gmail.com>', // sender address
to: to, // list of receivers
subject: subject, // Subject line
text: text, // plaintext body
html: html // html body
};
transporter.sendMail(mailOptions, function(error, infoo){
var res={
responsecode:''
}
if(error){
res.responsecode=401;
return info(new Error(res.responsecode),null);
}
res.responsecode=200;
info(null,res.responsecode+infoo.response);
});}
now call the function
app.get('/send',function (req,res) {
//pass value from your html form here
sendmail('to', 'subject', 'body', '<h1>its Html</h1>', function (err, info) {
if (err) {
console.log("Error is " + err)
return
}
console.log("Email sent. " + info)
})})

Categories