Sending data from html form to mysql table using node.js - mysql

I am trying to send data from my form to mysql database. My table has three columns minus the id column
This is the html for the form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>contact form</title>
</head>
<body>
<div id="page">
<form method="post" action="/myaction">
<label for="name">Enter name: </label>
<input id="name" type="text" name="name" value="<%= qs.person %>"> <br><br>
<label for="age">Enter age: </label>
<input id="age" type="number" name="age" value="<%= qs.year %>"><br><br>
<label for="department">Enter department: </label>
<input id="dept" type="text" name="department" value="<%= qs.dept %>"><br><br>
<input type="submit" value="OK">
</form>
<!--site javascript included-->
<script src="jquery-3.2.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="site.js"></script>
</div>
</body>
</html>
this is my node.js code, app.js:
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.set('view engine', 'ejs');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var con = mysql.createConnection({
host: "localhost",
user: "Name",
password: "XXXXXXXXXXXX",
database: "mydb"
});
app.get('/contact', function (req, res) {
res.render('contact', { qs: req.query });
});
app.post('/myaction', urlencodedParser, function (req, res) {
console.log(req.body);
var name = req.body.name;
var age = req.body.age;
var department = req.body.department;
con.connect(function (err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO 'customers' (name, age, department) VALUES (name, age, department)";
con.query(sql, function (err) {
if (err) throw err;
console.log("One record inserted");
});
});
res.render('contact-success', { data: req.body });
});
app.listen(3000, function () {
console.log('server running on port 3000');
});
When I enter some values into my form and run it, I get this error:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''customers' (name, age,
department) VALUES (name, age, department)' at line 1
I'm finding it difficult to figure it out. Any help please!!!

You should not add quotes around the table name.
Check on this.

Related

Cannot POST /ha use more then one FORM

I was trying to send more then one FORM, but I get an error.
The first FORM works the second one doesn't. It's the same form.
The second one gives me an error Cannot POST /ha
<body>
<form action="/ha" method="post">
<input type="text" name="user">
<input type="submit" value="Senden">
</form>
<form action="/Gehalt" method="post">
<input type="text" name="user">
<input type="submit" value="Senden">
</form>
</body>
this is my test.js
const sqlite3 = require('sqlite3').verbose();
const express = require('express');
const bodyParser = require('body-parser')
var app = express();
let Gehalt
let r
app.use(bodyParser.urlencoded({
extended: true
}));
let db = new sqlite3.Database('memory.sqlight3', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the chinook database.');
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/test.html');
});
app.post('/ha', function(req, res) {
console.log("Yout got it");
r = req.body.user;
var stmt = db.prepare('INSERT INTO lorem (Salary) VALUES(?);');
stmt.run(r);
stmt.finalize();
db.close();
});
app.post('/Gehalt', function(req, res) {
console.log("Yout got it");
r = req.body.user;
var stmt = db.prepare('INSERT INTO lorem (Outgoings) VALUES(?);');
stmt.run(r);
stmt.finalize();
db.close();
});
app.listen(3100, function() {
console.log('GO to Port 3100');
});
What did I do wrong?

Cannot GET error using angular js node.js and mysql

this is my index.html
i'm unable to get output while running npm start in the command prompt
i have tried using localost:8080 and localhost:8080/index.html
but the only output i'm getting is cannot get
<!DOCTYPE html>
<html lang="en">
<head>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/app.js"></script>
<script src="/Scripts/angular/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<form>
Author:
<input type="text" ng-model="author">
<br>
<br> Title:
<input type="text" ng-model="title">
<br>
<br> Body:
<input type="author" ng-model="body">
<br>
<br>
<input type="submit" value="Submit" ng-click="submit()">
</form>
</div>
</body>
</html>
this is my app.js file
i'm unable to get output while running npm start in the command prompt
i have tried using localost:8080 and localhost:8080/index.html
but the only output i'm getting is cannot get
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.submit= function(){
var data = $.param({
book: JSON.stringify({
author: $scope.author,
title : $scope.title,
body : $scope.body
})
});
$http.post("/api/book/", data).success(function(data, status) {
console.log('Data posted successfully');
})
}
});
This is server.js file
i'm unable to get output while running npm start in the command prompt
i have tried using localost:8080 and localhost:8080/index.html
but the only output i'm getting is cannot get
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydb'
});
connection.connect();
app.post('/api/book', function(req, res, next){
var cope = req.body.params;
var query = connection.query('insert into cope set ?', cope, function(err, result) {
if (err) {
console.error(err);
return res.send(err);
} else {
return res.send('Ok');
}
});
});
app.listen(8080);
console.log("listening");

How do I POST data into MongoDB database using node.JS?

the code below is pretty messy so don't judge too much! I am trying to POST a basic user profile into my database, i don't think i am far off but i keep getting a 404.
im pretty knew to all of these technologies so could somebody please enlighten me as to what i have done wrong.
node.js POST method
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/local';
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('signIn', { title: 'signIn' });
});
router.get('/getData', function(req, res, next){
mongo.connect(url, function (err, db) {
assert.equal(null, error);
var cursor = db.collection('userData').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function() {
db.close();
res.render('index', {items: resultArray});
} );
});
});
router.post ('/insert', function(req,res,next) {
var item = {
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
password: req.body.password
};
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('userData').insertOne(item, function (err, result) {
assert.equal(null, err);
console.log('item has been inserted');
db.close;
});
});
res.redirect('/');
});
module.exports = router;
form HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>SignIn Page</title>
<link rel="stylesheet" type="text/css" href="/stylesheets/signIn.css"/>
</head>
<body>
<div class="background">
<div class="loginFormWrapper">
<form action="/users/submit" method="POST">
<div class="loginForm">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="first name">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastName" name="lastName" placeholder="last name">
<label for="email">Email address:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="password" id="password" placeholder="password">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form action="users" method="GET">
<button type="submit" class="btn btn-default">get result</button>
</form>
</div>
</div>
</body>
</html>
App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var validate = require('form-validate');
var mongoose = require('mongoose');
var index = require('./routes/index');
var users = require('./routes/users');
var About = require('./routes/about');
var signIn = require('./routes/signIn');
var contact = require('./routes/contact');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/About', About);
app.use('/signIn', signIn);
// app.use('/contact', contact);
//catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
user.js
var express = require('express');
var app = require("mongoose");
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
A quick reminder, the post() method just gets the data from the <form> you specify. For you to be able to get that data you'd have to do something like this.
app.js
const express = require('express)
const mongoose = require('mongoose)
var app = express()
mongoose.connect('mongodb://localhost:"yourPortHere"/"mongoDBhere"')
Now post needs the body parser in order to be able to retrieve the data and sort of "translate it" to JS, for that you need the body parser.
app.use(bodyParser.urlencoded({extended: false})) //Post Body Parser
Now let's get to the post
app.post("/action", (req, res) => {
var userData = {
username: req.body.username,
password: req.body.password
}
For the moment userData is going to hold the data you just retrieved from the <form>
Remember that action="/YourActionHere is the identifier for the app.post("/YourActionHere") so those two have to match, otherwise you will not get the data.
To save it to MongoDB you first need to create a model of the object you want to store, if MongoDB has a Database named movies with a directory named films on it you first have to create a Model named film since mongoose will save it in the directory films (<- By directory I mean collection)
So: in folder Models you create a model of the object
const mongoose = require('mongoose')
const Schema = mongoose.Schema
var film = new Schema({
title: String,
year: String,
director: String
})
module.exports = mongoose.model("movie", movieSchema)
To be able to use that new Schema you have to import it in you app.js with
var Film = require('pathToFilmSchema')
Now in your post you will save userData to that Schema, and mongoose will store it in the collection specified in its .js.
app.post("/action", (req, res) => {
var userData = {
title: req.body."name",
year: req.body."name",
director: req.body.""
}
new Film(userData)
})
If the structure is the same de Data in that variable will be stored in a Schema, then you just have to call the method .save(), which you can call right after like this
newFil(userData)
.save()
Now mongoose will store a new object with film Schema into the database you have connected at the top. Keep in mind that, if you don't have a collection named film mongoDB will create one collection named films (the plural, always) and store the Schema there.
After saving you can res.redirect() to "/" or render another page, that's up to you.
You have posted to url users/submit but i don't see any API for users/submit . You have said to use users for /users urls but have you defined the /submit within /users?
You could go through this
Routing in expressjs
Inside your app.post function you should have something like this:
let MongoClient = require('mongodb').MongoClient;
let connectionUrl = "mongodb://localhost:27017/";
// or
// let connectionUrl = "mongodb+srv://<username>:<password>#<your-cluster-url>/test?retryWrites=true&w=majority";
// creating the message object
let obj = {"text" : "Something"};
console.log("OBJ: " + obj);
MongoClient.connect(connectionUrl, function(err, client) {
if (err) throw err;
console.log("Connected correctly to server");
// if database and collection do not exist they are created
var db = client.db('YourDatabase')
db.collection("YourCollection").insertOne(obj, function(err, res) {
if (err) throw err;
console.log("1 message inserted");
client.close();
});
});

how to insert data into database using MEAN stack (MySQL, Express, Angular, Node)

How to insert data into database using MEAN stack (MySQL, Express, Angular, Node)?
I am facing the problem at the time of insertion. Please help me to solve this. Here is my code. I'm newbie in MEAN.
index.html
<html ng-app="bookitnow">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<title> Registration Page </title>
</head>
<body>
<div class="container" ng-app="bookitnow" ng-controller="myCtrl">
<h1>Register</h1>
<form method="post">
<div class="form-group">
<input type="text" class="form-control" id="firstName" ng-model="fname" placeholder="First Name" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="lastName" ng-model="lname" placeholder="Last Name" required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" ng-model="email" placeholder="Email Address" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="phone" ng-model="phone" placeholder="Phone" required>
</div>
<button type="submit" class="btn btn-info" ng-click="submit()">Submit</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="controllers/controller.js"></script>
</body>
</html>
server.js
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'bookitnow'
});
connection.connect(function(err) {
if (!err)
console.log('Database is connected');
else
console.log('DB connection error.');
});
app.use(express.static(__dirname + '/public'));
app.get('/index.html', function(req, res){
res.sendFile(__dirname + '/public' + 'index.html');
});
app.post('/index.html', function(req, res, next) {
var data = req.body;
console.log('request received:', data);
connection.query('INSERT INTO register SET ?', data, function(err,res){
if(err) throw err;
console.log('record inserted');
});
app.listen(5500);
console.log('Hi from server.js');
controller.js
var app = angular.module('bookitnow',[]);
app.controller('myCtrl', function($scope,$http){
$scope.submit = function() {
var data = {
fName : $scope.fname,
lName : $scope.lname,
email : $scope.email,
phone : $scope.phone
}
};
$http.post('/index.html', &scope.data)
.success(function (data, status, headers, config) {
$scope.result = data;
console.log("inserted successfully")
})
.error(function(data, status, header, config){
$scope.result = "Data: " + status;
});
In your controller.js, try the following and see what happens.
var app = angular.module('bookitnow',[]);
app.controller('myCtrl', function($scope, $http){
$scope.submit = function() {
var data = {
fName : $scope.fname,
lName : $scope.lname,
email : $scope.email,
phone : $scope.phone
};
$http
.post('/index.html', data)
.then(function (response) {
console.log(response)
}, function(response){
console.log(response)
});
};
});

Insert data from form into MYSQL using Node JS

I am trying inserting the data into MySQL using node and Express framework from a HTML form. The code for the form is :
<html>
<head>
<title>Personal Information</title>
</head>
<body>
<div id="info">
<h1>Personal Information</h1>
<form action="/myaction" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email address" />
<br><br>
<label for="city">City:</label>
<input type="text" id="city" name="city" placeholder="Enter your city" />
<br><br>
<label for="pincode">Pincode:</label>
<input type="text" id="pincode" name="pincode" placeholder="Enter your pincode" />
<br><br>
<input type="submit" value="Send message" />
</form>
</div>
</body>
</html>
and the .js file is :
var express = require('express');
var app = express();
var ejs = require('ejs');
var mysql = require('mysql');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
var HOST = 'localhost';
var PORT = 3000
var MYSQL_USER = 'root';
var MYSQL_PASS = 'jelly123#';
var DATABASE = 'form';
var TABLE = 'info';
var mysql = mysql.createConnection({
host: HOST,
port: PORT,
user: MYSQL_USER,
password: MYSQL_PASS,
});
app.get('/home',function(req,res,next){
res.sendfile('views/forms.html');
});
app.post('/myaction', function(req, res) {
console.log('req.body');
console.log(req.body);
res.write('You sent the name "' + req.body.name+'".\n');
res.write('You sent the Email "' + req.body.email+'".\n');
res.write('You sent the City "' + req.body.city+'".\n');
res.write('You sent the Pincode "' + req.body.pincode+'".\n');
res.end()
mysql.query("Insert into "+TABLE+" (name,email,city,pincode) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.city+"','"+req.body.pincode+"')",function(err, result)
{
if (err)
throw err;
});
});
app.listen(3000);
console.log('Example app listening at port:3000');
I am able to enter the form data and display it in the page http://localhost:3000/myaction but unable to Insert data into database Please mention where I am doing wrong.
Thanks in advance.
var express = require('express');
var app = express();
var ejs = require('ejs');
var pg = require('pg');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
var conString = process.env.DATABASE_URL || "postgres://postgres:Emdsystems#localhost:5432/student";
var client = new pg.Client(conString);
client.connect();
app.get('/',function(req,res,next){
res.sendfile('views/forms.html');
});
app.post('/myaction', function(req, res) {
console.log('req.body');
console.log(req.body);
res.write('You sent the name "' + req.body.name+'".\n');
res.write('You sent the Email "' + req.body.email+'".\n');
res.write('You sent the City "' + req.body.city+'".\n');
res.write('You sent the Pincode "' + req.body.pincode+'".\n');
res.end()
client.query("Insert into record (name,email,city,pincode) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.city+"','"+req.body.pincode+"')",function(err, result)
{
if (err)
throw err;
});
});
app.listen(3000);
console.log('Example app listening at port:3000');
try this
mysql.query('select id, name, price from ' + TABLE + ' where price < 100',
function(err, result, fields) {
if (err) throw err;
else {
console.log('Gadgets which costs less than $100');
console.log('----------------------------------');
for (var i in result) {
var gadget = result[i];
console.log(gadget.name +': '+ gadget.price);
}
}
});
reference: http://www.hacksparrow.com/using-mysql-with-node-js.html
This my js file-
var express = require("express");
var app = express();
var path = require("path");
var mysql = require('mysql');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.post('/submit',function(req,res){
var name=req.body.name;
var email=req.body.email;
var username=req.body.username;
res.write('You sent the name "' + req.body.name+'".\n');
res.write('You sent the email "' + req.body.email+'".\n');
res.write('You sent the username "' + req.body.username+'".\n');
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO form (name, email,description) VALUES ('"+name+"', '"+email+"','"+username+"')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
res.end();
});
});
})
app.listen(3000);
console.log("Running at Port 3000");
This my html file-
<html>
<head>
<title> test </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form action="/submit" method="POST">
<fieldset>
<label for="name">Name: </label>
<input type="text" id="name" name="name" autofocus />
<br/>
<label for="email">Email: </label>
<input type="email" id="email" name="email" />
<br/>
<label for="username">User name: </label>
<input type="textbox" id="username" name="username" />
<br/>
<input type="submit" value="create profile" />
</fieldset>
</form>
</body>
</html>
You can try this
i am doing this with express js in node
pre-requisites:install node js,mysql,express,express-generator
Write this in index.jade file
<html>
<head>
<title> test </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form action="/submitform/" method="POST">
<fieldset>
<label for="name">Name: </label>
<input type="text" id="name" name="name" autofocus />
<br/>
<label for="email">Email: </label>
<input type="email" id="email" name="email" />
<br/>
<label for="description">Description: </label>
<textarea id="description" name="description"></textarea>
<br/>
<input type="submit" value="create profile" />
</fieldset>
</form>
</body>
</html>
Than ,write this in index.js file
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "testn"
});
router.post('/submitform', function(req, res, next) {
console.log(req.body.name);
console.log(req.body.email);
console.log(req.body.description);
con.connect(function(err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO `form`(`name`,`email`, `description`) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.description+"')";
con.query(sql, function(err, result) {
if(err) throw err;
console.log("table created");
});
});
res.render('index', { title: 'Express' });
});
module.exports = router;
This code will insert values from form into MySql in node js
Hope this will help you
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Registration Form</title>
<meta charset="utf-8">
<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">
<style>
.error{
color: red;
font-style: italic;
}
</style>
</head>
<body>
<button type='text' class="btn btn-primary" id="showbtn">Show/Hide Form</button>
<div class = "container">
<div class = "col-md-6 col-md-offset-3">
<div class = "panel panel-primary">
<div class = "panel-heading">
Registration
</div>
<div class = "panel-body">
<form id = "registration" action="http://127.0.0.1:7744/register">
<input type = "text" class = "form-control" name = "username" placeholder = "Username"/>
<br/>
<input type = "text" class = "form-control" name = "email" placeholder = "Email"/>
<br/>
<input type = "password" class = "form-control" name = "password" placeholder = "Password" id = "password"/>
<br/>
<input type = "password" class = "form-control" name = "confirm" placeholder = "Confirm Password"/>
<br/>
<input type = "text" class = "form-control" name = "fname" placeholder = "First Name"/>
<br/>
<input type = "text" class = "form-control" name = "lname" placeholder = "Last Name"/>
<br/>
<div class = "gender">
<label class="radio-inline"><input type="radio" value="male" name="gender" class = "form-contorl"/>Male</label>
<label class="radio-inline"><input type="radio" name="gender" value="female" class = "form-contorl"/>Female</label>
</div>
<br/>
<select class = "form-control" name = "city">
<option value="0" selected="" disabled="">--SELECT--</option>
<option>Delhi</option>
<option>Ghaziabad</option>
<option>Noida</option>
<option>Faridabad</option>
<option>GuruGram</option>
</select>
<br/>
<textarea class = "form-control" name = "address" placeholder="Address"></textarea>
<br/>
<button type = "submit" class = "btn btn-primary" >Submit</button>
</form>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.3/dist/jquery.validate.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script> $(document).ready(function () {
jQuery.validator.addMethod("noSpace", function (value, element) {
return value == '' || value.trim().length != 0;
}, "No space please and don't leave it empty");
jQuery.validator.addMethod("customEmail", function (value, element) {
return this.optional(element) || /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value);
}, "Please enter valid email address!");
$.validator.addMethod("alphanumeric", function (value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, and underscores only please");
var $registrationForm = $('#registration');
if ($registrationForm.length) {
$registrationForm.validate({
rules: {
username: {
required: true,
alphanumeric: true
},
email: {
required: true,
customEmail: true
},
password: {
required: true
},
confirm: {
required: true,
equalTo: '#password'
},
fname: {
required: true,
noSpace: true
},
lname: {
required: true,
noSpace: true
},
gender: {
required: true
},
country: {
required: true
},
address: {
required: true
}
},
messages: {
username: {
required: 'Please enter username!'
},
email: {
required: 'Please enter email!',
email: 'Please enter valid email!'
},
password: {
required: 'Please enter password!'
},
confirm: {
required: 'Please enter confirm password!',
equalTo: 'Please enter same password!'
},
fname: {
required: 'Please enter first name!'
},
lname: {
required: 'Please enter last name!'
},
country: {
required: 'Please select country!'
},
address: {
required: 'Please enter address!'
}
},
errorPlacement: function (error, element) {
if (element.is(":radio")) {
error.appendTo(element.parents('.gender'));
}
else {
error.insertAfter(element);
}
}
});
}else{
alert("submitted");
}
$('#showbtn').click(function () {
$('.container').fadeToggle('slow');
});
});
</script>
</body>
</html>
index.js Server
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'node_form'
});
connection.connect();
app.get('/', function (req, res) {
res.sendFile(__dirname + "/" + "index.html");
})
app.get('/register', function (req, res) {
var fname = req.query.fname;
var lname = req.query.lname;
var username = req.query.username;
var gender = req.query.gender;
var email = req.query.email;
var city = req.query.city;
var password = req.query.password;
var address = req.query.address;
var confirm = req.query.confirm;
var check = "select * from registration where email = '" + email + "' or username = '" + username + "'";
connection.query(check, function (err, result) {
if (err) {
throw err;
} else if (result.length !== 0) {
console.log("user already exist");
}
else {
var user = {
fname: fname,
lname:lname,
username:username,
gender:gender,
email:email,
city:city,
password:password,
address:address
};
if (password !== confirm) {
console.log("password and confirm password not match")
} else {
connection.query('insert into registration set ?', user, function (err, rs) {
if (err) throw err;
console.log('Form submitted successfully');
res.sendFile(__dirname + "/" + "index.html");
})
}
}
})
})
var server = app.listen(7744, function () {
console.log("server started");
})