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
Related
I created a database in cloud firestor,so now I want to add some information to it by input fields,
the problem when the input fields are empty information is stored and catch function does't work,how can I fix it,and make catch function work.
Here is the code:
HTML:
<div class="container">
<input type="text" placeholder="Enter the country" id="country-field" required>
<p class="selectPar">Enter City</p>
<input type="text" placeholder="Enter the city" id="city-field" required>
<p class="selectPar">Enter the place name</p>
<input type="text" placeholder="Enter the place name" id="placename-field" required>
<p class="selectPar">Enter Address</p>
<input type="text" placeholder="Enter the address" id="address-field" required>
</div>
</div>
<div id="btnFrmAlignSec">
<button id="btnFrm" type="button" onclick="AddToDataBase()">Send to admin</button>
</div>
Javascript
function AddToDataBase(){
var inputCountry = document.getElementById("country-field").value;
var inputCity = document.getElementById("city-field").value;
var inputAddress = document.getElementById("address-field").value;
var inputNameofPlace = document.getElementById("placename-field").value;
// Add a new document in collection "cities"
db.collection("UsersShare").doc().set({
name:inputNameofPlace,
city:inputCity,
country:inputCountry,
address:inputAddress,
})
.then(function() {
console.log("Document successfully written!");
document.getElementById("reply").style.display="inline";
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
if(inputCountry.trim() && inputCity.trim() && inputAddress.trim() &&
inputNameOfPlace.trim()){
// Add a new document in collection
// your code
} else {
// fields are empty --- error message
}
You can check before-hand if the fields are empty, if not then operate on the db, otherwise log error to the console as your catch function does:
if(inputCountry && inputCity && inputAddress && inputNameOfPlace){
db.coll.....
} else {
console.error('Field(s) are empty');
}
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.
I have an express website that has a form in it. That form allows us to send users information data to the database (mysql). It came to my attention that the submit functionality doesn't send any data to the database when we use Internet Explorer. The other browsers work perfectly fine. But IE sends nothing to the database. When the submit has been clicked with IE, the form sends us to the confirmation page indication submission is successful. But nothing inside the database. The code that I use is below. This is the admission.js router file.
router.post('/add-application', function (req, res) {
var first_name = req.body.first_name;
var middle_name= req.body.middle_name;
var last_name = req.body.last_name;
//check errors
req.checkBody('first_name', 'First name is required').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.render('/error', {
errors:errors,
first_name : first_name,
middle_name : middle_name,
last_name : last_name
});
} else {
var applications = {
first_name : first_name,
middle_name : middle_name,
last_name : last_name
};
}
var query = connection.query('INSERT INTO applications SET ?', applications, function (err, result) {
console.log('Error:' + err);
console.log('Success: ' + result);
});
req.flash('success_msg', 'Application Inserted!');
res.redirect('/');
});
And I have the following scripts for IE on the header as well:
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
And here is the form:
<div class="container">
<div class="row">
<h2>Register</h2>
<form class="form-register" method="post" action="/admission/add-application">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="fa fa-fw fa-check"></i>Information</h4>
</div>
<div class="panel-body">
<label>First Name</label>
<input name="first_name" type="text" class="form-control" placeholder="Enter the first name" required><br />
<label>Middle Name</label>
<input name="middle_name" type="text" class="form-control" placeholder="Enter the middle name" ><br />
<label>Last Name</label>
<input name="last_name" type="text" class="form-control" placeholder="Enter the last name" required ><br />
</div>
</div>
</div>
<div class="col-lg-12">
<input style="width:25%" class="btn btn-lg btn-primary btn-block" type="submit" name="submit" value="Submit" />
</div>
</form>
</div>
</div>
Internet Explorer 9 || < doesn't support major components. Websockets and submitting form functionalities are just two of them. So the solution is very simple. DO NOT use IE.
This is my first foray into Google scripts and I have a form that calls two different Google app scripts(both are in the .gs file). One Uploads a file while the other saves the form data to a google spreadsheet. For some reason I get an error when calling the file upload script
(Uncaught TypeError: Cannot read property 'closure_lm_407634' of null)
While the script that uploads the data works fine.
Saving the form data to spreadsheet(which works):
google.script.run.withUserObject(data).saveToSheet(data);
-- which calls:
function saveToSheet(data) {
var date = new Date();
var sheet = SpreadsheetApp.openById(submissionSSKey);
sheet
.appendRow([date, data.name, data.email, data.headline,
data.location, data.newsContent, data.websiteContent, data.expiry, data.fileUrl]);
}
Uploading file(doesn't work):
google.script.run
.withUserObject(theForm)
.withSuccessHandler(processForm)
.uploadFile(theForm);
-- which calls:
function uploadFile(form) {
var folder = DriveApp.getFolderById(folderId), doc = '', file = form.uploadedFile;
if (file.getName()) { doc = folder.createFile(file); }
return doc;
}
I can't for the life of me figure out why one call works while the other does not. I've tried every way I could think of to call the upload script but nothing works. I've tried removing the user object and success handler.
HTML:
<?!= include('styles'); ?>
<div id="container" class="col-lg-12 col-md-12 col-sm-12">
<header class="col-lg-offset-3 col-md-offset-3"></header>
<div class="col-lg-offset-3 col-lg-6 col-md-6 col-sm-12" id="form">
<h1 class="text-center">
SAS News Submission
</h1>
<span id="required-content">
<sup>*</sup>
Required
</span>
<br>
<br>
<form name="sas-form">
<label for="name" class="required">Contact Person/ Source of News</label>
<input type="text" name="name" value="test" class="form-control" id="name" required="required">
<br>
<label for="email" class="required">Contact Person's email (in case we have questions regarding your News content)</label>
<input type="email" name="email" value="me#me.com" id="email" class="form-control" required="required">
<br>
<label for="headline" class="required">Headline (try to keep below 10 words if possible) </label>
<input type="text" name="headline" value="headline" id="headline" class="form-control" required="required">
<br>
<label for="newsContent" class="required">News Content *Note all content must be fully edited to ensure posting</label>
<textarea rows="5" cols="0" name="newsContent" class="form-control" id="newsContent" required="required">
Content
</textarea>
<br>
<label class="required">Where would you like the News to be shared? (You may choose more than one)</label>
<ul id="social-list">
<li>
<input type="checkbox" name="newsletter" id="newsletter" value="newsletter">
<label for="newsletter"> Newsletter</label>
</li>
<li>
<input type="checkbox" name="social" id="social" value="social">
<label for="social"> Social Media (Facebook, LinkedIn, Twitter)</label>
</li>
<li>
<input type="checkbox" name="website" id="website" value="website" checked>
<label for="website"> Website </label>
</li>
</ul>
<br>
<label for="websiteContent">If you chose the website, please provide specific instructions on where you would like the content to be posted.</label>
<br>
<small>News and Events Page, Volunteer Page, Student Page, etc. Ex: Please post in the News and Events Page and send the link and headline out on social media.</small>
<textarea rows="5" cols="0" name="websiteContent" id="websiteContent" class="form-control">website content</textarea>
<br>
<label for="expiry">If your content has an expiration date, please share that date below.</label>
<input type="date" name="expiry" id="expiry" class="form-control">
<br>
<label>If you have files that need to be attached, pick them below.</label>
<input type="file" name="uploadedFile" id="file">
<br>
<div id="not-valid"><span></span></div>
<div id="error"><span>
An error occurred, please try submitting again.
</span></div>
<div id="success"><span>
Form submission was successful! Thank you!
</span></div>
<input type="button" value="Submit" class="btn btn-primary" id="submit"
onclick="validateForm(this.parentNode)">
</form>
</div>
</div>
<footer>
<?!= include('javascript'); ?>
</footer>
<script>
var validateForm = function(theForm)
{
var valid = true;
$('#not-valid span').empty();
$('input').removeClass('warning');
if($('#name').val() == '')
{
$('#name').addClass('warning');
$('#not-valid span').append('Please enter a name <br>');
valid = false;
}
if($('#email').val() == '')
{
$('#email').addClass('warning');
$('#not-valid span').append('Please enter an email <br>');
valid = false;
}
if($('#headline').val() == '')
{
$('#headline').addClass('warning');
$('#not-valid span').append('Please enter a headline <br>');
valid = false;
}
if($('#newsContent').val() == '')
{
$('#newsContent').addClass('warning');
$('#not-valid span').append('Please enter news content <br>');
valid = false;
}
if(!$('#social').is(':checked') && !$('#website').is(':checked') && !$('#newsletter').is(':checked'))
{
$('#not-valid span').append('Please choose where you would like the news to be shared. <br>');
$('#social-list').addClass('warning');
valid = false;
}
if(valid)
{
google.script.run.withSuccessHandler(processForm).uploadFile(theForm)
}
};
function processForm(file)
{
var fileUrl = file ? file.getUrl() : 'No file uploaded',
location = [];
if($('#social').is(':checked'))
{
location.push('social');
}
if($('#newsletter').is(':checked'))
{
location.push('newletter');
}
if($('#website').is(':checked'))
{
location.push('website');
}
var data = {
name: $('#name').val(),
email: $('#email').val(),
headline: $('#headline').val(),
location: location.toString(),
newsContent: $('#newsContent').val(),
websiteContent: $('#websiteContent').val(),
expiry: $('#expiry').val() ? $('#expiry').val() : 'No expiration date selected',
fileUrl: fileUrl
};
google.script.run.saveToSheet(data);
clearForm();
success();
};
var clearForm = function()
{
$("input[type=text], input[type=date], textarea, input[type=email], input[type=file]").val("");
$("input[type=checkbox]").attr('checked', false);
enableSubmit();
};
var success = function()
{
$('#success').show()
};
var enableSubmit = function()
{
$("#submit").prop('disabled', false);
};
</script>
I was able to reproduce your error. I have no idea why that error is occurring, but I found a way to make it work.
Here is what you need to do:
Put an id attribute into the upper form tag:
<form id="myForm">
Remove the button using an input tag.
Add a <button> tag outside of the form. Must be outside of the form. And get the form with document.getElementById('myForm')
<form id="myForm">
<input type="file" name="uploadedFile">
</form>
<button onclick="validateForm(document.getElementById('myForm'))">submit</button>
I've tested this. It got the file, and sent it to the server inside of the form element.
You can use Logger.log() in the server code without using the debugger.
function uploadFile(form) {
Logger.log('form: ' + form);
Logger.log('form.uploadedFile: ' + form.uploadedFile);
Logger.log('form.uploadedFile: ' + form.uploadedFile.getName());
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");
})