How can i move value from angular form to server nodejs - html

- 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.

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.
....................................................................................................................................................................................................................................................................................................................................................................................................................................................................

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

AngularJS hiding input field

I am writing a login page with register and login options using AngularJS. There are three input fields: username, password and name. I want name field to appear when I click to register button and disappear when I click to login button. Therefore I want to change input field's class to 'hidden' on click and let css handle the job. How can I do it using AngularJS? Is there a better way to hide the name input field?
HTML:
<h2>Welcome to Mail Service</h2>
<form action="/action_page.php">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>
<!-- NAME INPUT FIELD -->
<div class="textField-hidden">
<label><b>Name</b></label><br>
<input type="text" placeholder="Enter Name" ng-model="user.name">
</div><br>
<button type="submit" ng-click="login()">Login</button><br>
<button type="submit" ng-click="register()">Register</button>
</div>
</form>
AngularJS Controller:
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.login = function()
{
var loginRequest = $resource('/api/login');
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
var registerRequest = $resource('/api/register');
loginRequest.save($scope.user, function(response)
{
});
};
}]);
You need to use ng-hide or ng-show directive (based on your context), and provide it with appropriate condition value like this:
$scope.showName = false;
$scope.login = function() {
// Your code
$scope.showName = false;
}
$scope.register = function() {
// Your code
$scope.showName = false;
}
Change your HTML accordingly:
<input ng-show="showName" type="{{type}}" placeholder="Enter Name" ng-model="user.name">
In this way, the input box will be shown only if the expression of ng-show evaluates to true. Alternatively, ng-if can be used similar to ng-show, but it works a bit different.
just populate a variable as true when you click register and set that variable as false when you click login.
<h2>Welcome to Mail Service</h2>
<form action="/action_page.php">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>
<!-- NAME INPUT FIELD -->
<div class="textField-hidden" ng-show="register">
<label><b>Name</b></label><br>
<input type="text" placeholder="Enter Name" ng-model="user.name">
</div><br>
<button type="submit" ng-click="login()">Login</button><br>
<button type="submit" ng-click="register()">Register</button>
now populate $scope.register as true when you click register
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.register=false;
$scope.login = function()
{
var loginRequest = $resource('/api/login');
$scope.register=false;
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
var registerRequest = $resource('/api/register');
$scope.register=true;
loginRequest.save($scope.user, function(response)
{
});
};
}]);
You can use a variable for input fields type and hide it
HTML:
<input type="{{type}}" placeholder="Enter Name" ng-model="user.name">
JS:
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.login = function()
{
$scope.type="hidden";
var loginRequest = $resource('/api/login');
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
$scope.type="text";
var registerRequest = $resource('/api/register');
loginRequest.save($scope.user, function(response)
{
});
};
}]);
An alternative will be to use ng-if or ng-hide/ng-show defined on a $scope variable and trigger a boolean value for this variable according to your needs.

How to insert form data in to mysql using express ejs

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...