Angular json array data not inserting in mysql db using node js - javascript

I am creating a Json object. Inside that I am creating an array, the array will push some fields dynamically when user clicks add buttons, I want to store the dynamic fields values in scope variable called table and passing that to submit() function, so when the user clicks the save button it calls the submit() function, where it send that field values to node using $http.
The values which is sent to node js server is not inserting in tables
HTML
<form ng-controller="NewTableCtrl" ng-app="myApp" name="frm" class="form-inline" ng-submit="submitTable()">
<input type="string" name="cat_name" class="form-control" ng-model="table.cat_name" placeholder="Enter Category Name" ng-pattern="/^[a-zA-Z]*$/" required>
<input type="text" name="cat_desc" class="form-control" ng-model="table.cat_desc" placeholder="Enter Your Description" ng-pattern="/^[a-zA-Z]*$/" required>
<input type="disable" class="form-control" name="count" ng-model="table.fields.length">
<fieldset ng-repeat="field in table.fields track by $index" >
<input type="text" ng-model="table.fields[$index].item_name" class="form-control" name="item_name" placeholder="Category Item Name" ng-pattern="/^[a-zA-Z]*$/" required>
<input type="text" ng-model="table.fields[$index].item_desc" class="form-control" name="item_desc" placeholder="Category Item Description" ng-pattern="/^[a-zA-Z]*$/" required>
<input type="number" ng-model="table.fields[$index].item_count" class="form-control" name="item_count" ng-pattern="/^[0-9]/" placeholder="Category Item View Count" required>
<div class="form-group move-down">
<label for="Autocomplete">Generic Autocomplete</label>
<input type="text" id="Autocomplete" class="form-control" ng-autocomplete="table.fields[$index].result1" details="details1" options="options1"/>
</div>
<span class="help-block well" ng-show="frm.item_count.$error.pattern">numbers only allowed</span>
<button ng-click="removeChoice()" class="remove btn btn-danger" >close</button>
</fieldset>
<!-- <button ng-click="removeChoice()" >close</button> -->
<div>
<button class="addfields btn btn-success" ng-disabled="!frm.cat_name.$dirty||!frm.cat_desc.$dirty||frm.cat_desc.$invalid||frm.cat_name.$inavalid||!frm.item_name.$dirty||frm.item_name.$invalid||!frm.item_desc.$dirty||frm.item_desc.$invalid||!frm.item_count.$dirty||frm.item_count.$invalid" ng-click="submit(table)">Save</button>
<button class="addfields btn btn-success" ng-click="addFormField()" ng-disabled="!frm.cat_name.$dirty||!frm.cat_desc.$dirty||frm.cat_desc.$invalid||frm.cat_name.$inavalid">Add fields</button>
</div>
<span class="help-block" class="well" style="color:red" ng-show="frm.cat_desc.$error.pattern">ERROR:<BR/>text only allowed</span >
<span class="help-block" class="well" style="color:red" ng-show="frm.cat_name.$error.pattern">ERROR:<BR/>text only allowed</span >
<span class="help-block" style="color:red" ng-show="frm.item_desc.$error.pattern">ERROR:<BR/>text only allowed</span >
<span class="help-block" style="color:red" ng-show="frm.item_name.$error.pattern">ERROR:<BR/>text only allowed</span >
<pre>{{ table | json }}</pre>
</form>
Angular Code
var app = angular.module('myApp', ['ngAutocomplete']);
app.controller('NewTableCtrl', function($scope,$http) {
var counter=0;
$scope.table = { fields: [] };
$scope.addFormField = function() {
$scope.table.fields.push('');
}
$scope.submitTable = function() {
console.log($scope.table);
}
$scope.removeChoice = function() {
$scope.table.fields.splice(this.$index,1);
};
$scope.result1 = '';
$scope.options1 = null;
$scope.details1 = '';
$scope.details3 = '';
$scope.submit=function(category){
$http({method:"post",url:"http://localhost:3000/insert",data:category})
.then(function(data){
/* Success callback */
alert("Data hase been entered!");
// console.log("success");
},function(err){
/* Failure callback */
alert("Something went wrong!");
});
}
});
Node
var mysql=require('mysql');
var http=require('http');
var uuid = require('node-uuid');
var path=require('path');
var express=require('express');
var app=express();
var bodyparser=require('body-parser');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: true}));
var myconnection = mysql.createConnection({
host : "localhost",
user : "root",
password : "",
database : "siva"
});
app.use(express.static(__dirname + ""));
var uqid= uuid.v1();
var it_id=uuid.v4();
var tt=1;
var status="active";
app.post("/insert",function(req,res){
console.log(req.body);
/* TODO: Now just check that your drive function is correct, SQL is correct and whether what arguements passed to SQL callback is correct */
myconnection.query('Insert into cate_tbl (cat_id,cat_name,cat_desc,cat_view_count,cat_status) VALUES ("'+uqid+'","'+req.body.cat_name+'","'+req.body.cat_desc+'","'+tt+'","'+status+'")',function(err, results, fields) {
//if (err) throw err;
if (err) {console.log("DB Error"+err); res.send("add failed"+err);}
else res.send("add success");
});
myconnection.query('Insert into cate_item (cat_it_id,cat_it_name,cat_pid,cat_it_count,cat_it_desc,cat_it_status) VALUES ("'+it_id+'","'+req.body.item_name+'","'+uqid+'","'+req.body.tem_count+'","'+req.body.item_desc+'","'+status+'")',function(err, results, fields) {
//if (err) throw err;
if (err) {console.log("DB Error"+err); res.send("add failed"+err);}
else res.send("add success");
});
});
app.get('/',function(req,res){
res.sendfile("index.html");
});
app.listen(3000,function(){
console.log("It's Started on PORT 3000");
})

Related

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 insert data to MySQL using HTML & Node JS?

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.

Node and Angular form conditions

I have A front end Angular form, with Node reviving the data on the back end.
I have conditions on the from in the front end written in Angular, I would like have some extra conditions that would display with a new button to replace the submit button if the post was successful.
dose anyone know how I would do this ? I was thinking something like ng-hide/show show text and button and hide form and submit button on form completion.
Node Code
var firstFunction = function () {
var promise = new Promise(function (resolve) { // may be redundant
setTimeout(function () {
app.post('/api/data', function (req, res) {
console.log(req.body);
// Get varibles from the post form
var email_user = req.body.email;
var first_name = req.body.fname;
var last_name = req.body.lname;
// res.send(email_user);
res.send(first_name + ' ' + last_name + ' ' + email_user);
//resolve when get the response
resolve({
data_email: email_user,
data_first_name: first_name,
data_last_name: last_name
});
});
}, 2000);
});
return promise;
};
Angular code (view)
<div class="form-group">
<label for="first-name">First Name*</label>
<input type="text" class="form-control col-sm-12" name="Fname" placeholder="Enter first name"
ng-model="formData.Fname"
ng-required="true">
<span ng-if="!myForm.Fname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Last Name*</label>
<input type="text" class="form-control col-sm-12" name="Lname" placeholder="Enter last name"
ng-model="formData.Lname"
ng-required="true">
<span ng-if="!myForm.Lname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Email*</label>
<input type="email" class="form-control col-sm-12" name="email" placeholder="Enter valid E-mail"
ng-model="formData.email"
ng-required="true">
<span ng-if="!myForm.email.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group row">
<div class="col-xs-6 col-xs-offset-3">
<button type="submit" class="btn btn-block btn-info"
ng-disabled="!myForm.$valid">
Submit <span class="glyphicon glyphicon-circle-arrow-right"></span>
</button>
</div>
Angular code (controller)
FirstModule.controller('formController', function ($scope, $http) {
$scope.formData = {};
$scope.processForm = function (Fname, Lname, email) {
var data = {
fname: $scope.formData.Fname,
lname: $scope.formData.Lname,
email: $scope.formData.email
};
//Call the services
//Change http://localhost:8080/api/data to /api/data when live
$http.post('http://localhost:8080/api/data', JSON.stringify(data)).then(function (response) {
if (response.data)
$scope.formData = "Post Data Submitted Successfully!";
}, function (response) {
$scope.formData = "Post Data Submitted Failed";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});

Categories