How to insert form data in to mysql using express ejs - mysql

I am new to Node.JS, so I created a form in express ejs in views/pages/profile.ejs as follow:
<form role="form" action="/profile" method="post">
<div class="box-body">
<h4>Generl Details</h4>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="email" class="form-control" placeholder="Email" name="email_id">
</div>
<br/>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input type="text" class="form-control" placeholder="First Name" name="first_name">
</div>
<br/>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input type="text" class="form-control" placeholder="Last Name" name="last_name">
</div>
<div class="form-group">
<label>Address</label>
<textarea class="form-control" rows="3" name="address" placeholder="Enter you Address ..."></textarea>
</div>
<div class="form-group">
<label>Gender</label>
<select class="form-control">
<option>Male</option>
<option>Female</option>
</select>
</div>
</div><!--/.col (left) -->
<!-- right column -->
<div class="box-footer">
<input type="submit" class="btn btn-primary" id="profilesubmit" value="submit">
</div>
</form>
I want to insert this form in the MySql database on submit.
I have create a dbquery/index.js for all DB queries. This file looks like:
// load up the user model
var mysql = require('mysql');
var bcrypt = require('bcrypt-nodejs');
var dbconfig = require('../config/database');
var connection = mysql.createConnection(dbconfig.connection);
connection.query('USE ' + dbconfig.database);
var express = require('express');
var app = express();
var bodyParser = require('body-parser')
/*app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
})); */
app.use(express.bodyParser()); // get information from html forms
module.exports = function(dbquery) {
app.post("/profile", function(req, res){
connection.query("SELECT * FROM users WHERE username = ?",[username], function(err, rows) {
if (err)
return done(err);
if (rows.length) {
return done(null, false, req.flash('signupMessage', 'That username is already taken.'));
} else {
// if there is no user with that username
// create the user
console.log(req.body.first_name);
var newUserMysql = {
email_id : req.body.email_id,
first_name : req.body.first_name, // use the generateHash function in our user model
last_name : req.body.last_name
};
var insertQuery = "INSERT INTO users ( email_id, first_name, last_name ) values (?,?)";
res.send(connection.query(insertQuery,[newUserMysql.email_id, newUserMysql.first_name, newUserMysql.last_name],function(err, rows) {
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
}));
}
});
});
};
This all I have done for inserting data in to MySQL.
Nothing is added into table. Also let me know if any other details needed.
Any help on this will be great.
Thank you...

Related

Form data to accept nested schema in Javascript

I have a JSON schema which i am trying to make my form tailor, but the schema has nested objects and arrays like so:
{
"person": {
"firstName":"Kay",
"lastName":"Young"
}
"addressDetails":[
{
"line1": "line1",
"line2": "line2"
}]
}
HTML
<div class="form-group">
<label for="caseIdentifier">First Name</label>
<input type="text" class="form-control" id="firstname" name="?">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" id="lastName" name="?">
</div>
<div class="form-group">
<label for="line1">Line 1</label>
<input type="text" class="form-control" id="line1" name="?">
</div>
<div class="form-group">
<label for="line2">Line 2</label>
<input type="text" class="form-control" id="line2" name="?">
</div>
JS
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function (e) {
e.preventDefault();
const url = url;
const formData = new FormData(this);
let object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
let json = JSON.stringify(object);
let fetchData = {
method: 'POST',
body: json,
headers: <myHeaders>
}
fetch(url, fetchData)
.then(function (response) {
console.log(fetchData)
return response.text();
}).then(function (text) {
console.log(text);
}).catch(function (error) {
console.error(error);
});
});
How do I tailor my HTML form to match these parameters in JS? please.
....................................................................................................................................................................................................................................................................................................................................................................................................................................................................

I cannot show my output JSON file from server in an HTML page

Here's my server side code snippet (backend):
const express = require('express');
const bodyparser = require('body-parser');
const path = require('path');
const mongoose = require('mongoose');
const { quotemodel } = require('./model/user')
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/qouteDB', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
let app = express();
app.use(express.static(__dirname + '/public'));
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, './public/quotes/qoutes.html'))
})
app.post('/post', (req, res) => {
let newQoute = new quotemodel();
newQoute.title = req.body.title;
newQoute.author = req.body.author;
newQoute.body = req.body.body;
newQoute.save(function(err, savedObject) {
if (savedObject) { res.redirect('/viewquotes/' + req.body.author) } else { res.send(err) }
})
})
app.get('/viewquotes/:author', (req, res) => {
console.log('Salam');
quotemodel.findOne({ author: req.params.author }).then((quotemodel) => {
if (!quotemodel) {
res.send().json({
Error: 'Something Went Wornd' + err
})
}
let data = ({
title: quotemodel.title,
author: quotemodel.author,
date: quotemodel.createdAt,
body: quotemodel.body
})
res.send(data)
console.log(data);
})
})
When I run the server and get to localhost:3001/ my HTML page is loading on the port. I can enter my data and I use the (author) item form inserting in url. Next, I use the (author) as param I can access to MongoDB database and I can get my specific data and send it as JSON.
My question
I want the following points:
When redirect to (/viewquotes/:author) my second page(OutPut) open
and when the second page is opened my JSON data rendered into Form
Here is my model:
const mongoose = require('mongoose');
const PersianDate = require('persian-date');
PersianDate.toLocale('en')
let DateAt = new PersianDate().format('YYYY/MMMM/DD')
var qouteschema = mongoose.Schema({
author: String,
body: String,
title: String,
createdAt: { type: String, default: DateAt }
})
let quotemodel = mongoose.model('quotemodel', qouteschema);
module.exports = {
quotemodel
}
this is my HTML Form For Input
<form action="/post" method="POST">
<input id="title" name="title" type="text">
<input id="body" name="body" type="text">
<input id="author" name="author" type="text">
<input id="send" value="send" type="submit">
</form>
This my HTML Form for OutPut
<body>
<div>
<input type="text" name="author" id="author">
<input type="text" name="body" id="body">
<input type="text" name="title" id="title">
<input type="date" name="time" id="time">
<input type="button" onclick="NewIncom()">
</div>
<div class="viewquotes"></div>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="../viewqoutes.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function NewIncom() {
axios.get('http://http://localhost:3001/viewquotes')
.then(function(response) {
// handle success
document.getElementById("author").value = response.data.author;
document.getElementById("body").value = response.data.body;
document.getElementById("title").value = response.data.title;
document.getElementById("time").value = response.data.date;
})
}
</script>
Sounds like you need a templating engine for your html pages. Then you could use the data you send with the response to populate fields.
EJS is really easy to use. https://github.com/tj/ejs
Then you could do something like:
<% if (quote) { %>
<form action="/post" method="POST">
<input id="title" name="title" type="text" value="<% quote.title %>">
<input id="body" name="body" type="text" value="<% quote.body %>">
<input id="author" name="author" type="text" value="<% quote.author %>">
<input id="send" value="send" type="submit">
</form>
<% } %>

Store null values in database while trying to save data using spring mvc angular js

angular js code
<body data-ng-app="myApp" data-ng-controller="UserController as userBean">
<form method="post" action="register" name="myForm">
<div class="form-group col-lg-7" >
<label for="username" class="control-label">First Name:</label>
<input type="text" data-ng-model="userBean.username" class="form-control" placeholder="Enter Firstname"/><br>
<label for="phone" class="control-label">Phone:</label>
<input type="text" data-ng-model="userBean.phone" class="form-control" placeholder="Enter phone no."/><br>
<label for="email" class="control-label">Email:</label>
<input type="text" data-ng-model="userBean.email" class="form-control" placeholder="Enter email"/><br>
<label for="address" class="control-label">Address:</label>
<input type="text" data-ng-model="userBean.address" class="form-control" placeholder="Enter address"/><br>
<label for="password" class="control-label">Password:</label>
<input type="password" data-ng-model="userBean.password" class="form-control" placeholder="Enter password"/><br>
</div>
<div class="form-group col-lg-7">
<button type="submit" data-ng-click="insertData()" class="btn btn-primary">Submit</button>
</div>
</form>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller("UserController", ['$scope', '$http', function($scope, $http, httpPostService) {
var self=this;
$scope.insertData = function()
{
alert($scope.userBean.username, $scope.userBean.phone, $scope.userBean.email);
$http({
method: "POST",
url: "register",
data:{
username: $scope.userBean.username,
phone: $scope.userBean.phone,
email: $scope.userBean.email,
address: $scope.userBean.address,
password: $scope.userBean.password}
}).then(function(response){
console.log(response.status);
console.log("in success");
}, function(response){
console.log(response.status);
console.log("in fail");
});
};
}]);
</script>
controller code
#RequestMapping(value="/register", method = RequestMethod.POST, consumes="application/json")
public #ResponseBody ModelAndView doRegister(#ModelAttribute #RequestBody UserBean userBean, BindingResult result)
{
if(!result.hasFieldErrors())
{
if(retrieveService.insert(userBean) != null)
{
System.out.println("done");
}
}
return new ModelAndView("redirect:/welcome");
}
}
I think a controller problem. userBean has null values to pass it to a controller. so kindly anyone helps me
It error also came
HTTP Status 415 – Unsupported Media Type The origin server is refusing to service the request because the payload is in a format not
supported by this method on the target resource.
Set content type JSON in your request headers like below.
$http({
method: "POST",
url: "register",
data:{
username: $scope.userBean.username,
phone: $scope.userBean.phone,
email: $scope.userBean.email,
address: $scope.userBean.address,
password: $scope.userBean.password},
headers: {'Content-Type': 'application/json'}
})
Use #JsonIgnore on the field which can have null values.

Req.File.Path is undefined

I am trying to use multer to upload an image to a mysql database , and I am getting an error stating
TypeError: Cannot read property 'path' of undefined
my App.js
var multer = require('multer');
app.use(express.static("public"));
app.post("/updateImage/add",multer({ dest: './public/uploads/'}).single('img') ,contentUpdate.addImage);
my contentUpdate.js
exports.addImage = function(req, res) {
var path = (req.file.path).replace("public/", '');
console.log(path);
var data =
{
image: path
};
var URLs = data.PageURL;
connection.query('INSERT INTO `updatedimages` SET ?', [data], function(err, rows)
{
if (err)
{
console.log(err);
} else
{
req.flash('success','Entry Successful');
return res.redirect(URLs);
}
});
};
my updateImage.handlebars
<form id="myForm" action='/updateImage/add' method='POST' >
<div class="col-md-12" >
<input name='img' type="file" class="form-control" required/>
</div>
<div>
<button type="submit" class="glyphicon glyphicon-submit btn btn-primary ">
</div>
You need to set the proper encoding type in the HTML:
<form id="myForm" action='/updateImage/add' method='POST' enctype='multipart/form-data'>
Even so, it's always good to also validate the input:
if (! req.file || ! req.file.path) {
return res.sendStatus(400);
}
Change the following:
<input name='img' type="file" class="form-control" required/>
to
<input name='file' type="file" class="form-control" required/>
And then try:
app.post("/updateImage/add",multer({ dest: './public/uploads/'}).single('file') ,contentUpdate.addImage);

How can i move value from angular form to server nodejs

- This is the html:
<body ng-controller="stripeController">
<form action="/stripe" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="from-row">
<lebel>
<span>Price:{{getTotal}}$</span>
<input type="hidden" data-stripe="number">
</lebel>
</div>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="number" size="20" data-stripe="number">
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YY)</span>
<input type="text" size="2" data-stripe="exp_month">
</label>
<span> / </span>
<input type="text" size="2" data-stripe="exp_year">
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc">
</label>
</div>
<input type="submit" class="submit" value="Submit Payment">
</form>
</body>
This is the controller code:
app.controller('stripeController', function($scope, $http) {
$http.get('/api/me').success(function (response) {
$scope.userInfo = response;
$scope.isCartEmpty = true;
$scope.userCart = [];
if($scope.userInfo.cart.length>0){
$scope.isCartEmpty= false;
}
console.log($scope.isCartEmpty);
for(var i=0;i<$scope.userInfo.cart.length;i++){
$scope.userCart[i] = $scope.userInfo.cart[i].productId
}
var y = 0;
$scope.getTotal =0;
for(i=0;i<$scope.userCart.length;i++) {
$http.get('/api/product/' + $scope.userCart[i]).success(function
(response) {
$scope.userInfo.cart[y].name = response.name;
$scope.userInfo.cart[y].price = response.price;
$scope.getTotal+= response.price;
y++;
});
}
});
});
This is the node.js post function :
router.post('/stripe', function(req, res){
//Need to check if the cart empty than re-direct to catalog.
var stripe = require("stripe")(
"sk_test_mypass"
);
stripe.charges.create({
amount: ????? * 100,
currency: "usd",
source: req.body.stripeToken, // obtained with Stripe.js
description: "Test Charge"
}, function(err, charge) {
if(err){
console.log("Error");
}
console.log("Successfully bought product!");
});
});
-I have 1 questions:
In the node.js function where I put "?????" how can I get data from the
html form. When I type req.body.getTotal I don't get the data...
You'll want to send it in a hidden field, but it would be better to calculate the total from the product IDs and quantities in the Cart on the server side so there's no opportunity for the amount to be changed client side.