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');
}
Related
I'm working with DOM and web API to POST some information about the company like name, worker's name.
But when I write something in the input DOM can't reach the value and return empty so I post an empty object.
That looks like :
adress: ""
companyName: ""
contactName: ""
contactTitle: ""
My form block:
<form>
<div class="form-group">
<label for="">Company Name</label>
<input
type="text"
class="form-control"
id="companyName"
placeholder="Company Name!"
/>
</div>
<div class="form-group">
<label for="">Contact Name</label>
<input
type="text"
class="form-control"
id="contactName"
placeholder="Contact Name!"
value=""
/>
</div>
<div class="form-group">
<label for="">Contact Title</label>
<input
type="text"
class="form-control"
id="contactTitle"
placeholder="Contact Title!"
/>
</div>
<div class="form-group">
<label for="">Country</label>
<input
type="text"
class="form-control"
id="inputCountry"
placeholder="Country!"
/>
</div>
</form>
And my JS code:
'use strict';
let inputCompanyName = document.getElementById('companyName');
let inputContactName = document.getElementById('contactName');
let inputContactTitle = document.getElementById('contactTitle');
let country = document.getElementById('inputCountry');
const btnSubmit = document.getElementById('submit');
let newCompany = {
companyName: inputCompanyName.value,
contactName: inputContactName.value,
contactTitle: inputContactTitle.value,
adress: country.value,
};
btnSubmit.addEventListener('click', e => {
e.preventDefault();
axios
.post('https://northwind.vercel.app/api/suppliers', newCompany)
.then(res => {
console.log('Response', res.data);
alert('Success!');
});
});
I tried innerHTML and innerText and form method but I cant solve this problem.
You're reading the values immediately upon loading the page, long before the user has had a chance to enter any values.
Instead, read the values in the click event:
btnSubmit.addEventListener('click', e => {
let newCompany = {
companyName: inputCompanyName.value,
contactName: inputContactName.value,
contactTitle: inputContactTitle.value,
adress: country.value,
};
// the rest of the click handler logic...
});
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
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");
})
I am new to meteor and I am trying to do recover password and change password in Meteor. I will post below the code I have used to do this. I do get the template rendered, but the passwords do not change. Can anyone please help me with this? I am using the package accounts-password.
Custom-useraccounts.html:
<template name="RecoverPassword">
<form id="set-new-password">
<label for="new-password">New Password</label>
<input type="password" id="new-password" placeholder="Try not to forget this one.">
<input type="submit" value="Set New Password">
<p id="form-messages"></p>
</form>
<form id="forgot-password">
<label for="user-email">Email</label>
<input type="text" id="user-email" placeholder="Email">
<input type="submit" value="Get Reset Password Instructions">
<p id="form-messages"></p>
</form>
</template>
<template name="ChangePassword">
<form id="change-password">
<label for="current-password">Current Password</label>
<input type="password" id="current-password" placeholder="Current Password">
<label for="new-password">New Password</label>
<input type="password" id="new-password" placeholder="New Password">
<label for="new-password-repeated">Repeat New Password</label>
<input type="password" id="new-password-repeated" placeholder="Repeat New Password">
<input type="submit" value="Update Password">
<p id="form-messages"></p>
</form>
</template>
custom user-accounts.js:
if (Meteor.isServer) {
Template.RecoverPassword.events({
'submit #change-password': function(event, template) {
var currentPassword,
newPassword,
newPasswordRepeated;
currentPassword = template.find('#current-password');
newPassword = template.find('#new-password');
newPasswordRepeated = template.find('#new-password-repeated');
if (newPassword !== newPasswordRepeated) {
template.find('#form-messages').html("The new passwords don't match!");
return false;
}
if (Meteor.isServer) {
if (Accounts._resetPasswordToken) {
Session.set('resetPasswordToken', Accounts._resetPasswordToken);
}
Template.RecoverPassword.helpers({
resetPassword: function() {
return Session.get('resetPasswordToken');
}
});
Template.RecoverPassword.events({
'submit #forgot-password': function(event, template) {
event.preventDefault();
var email = template.find('#user-email'),
message;
alert(email);
if (email) {
Accounts.forgotPassword(email);
message = 'Sent a reset password link to ' + email + '.';
} else {
message = 'Please enter a valid email address.'
}
template.find('#form-messages').html(message);
return false;
},
'submit #set-new-password': function(event, template) {
event.preventDefault();
// Proper decoupled validation would be much nicer than this
var password = template.find('#new-password').value,
passwordTest = new RegExp("(?=.{6,}).*", "g");
if (passwordTest.test(password)) {
Accounts.resetPassword(
Session.get('resetPasswordToken'),
password,
function(error) {
if (err) {
template.find('#form-messages').html('There was a problem resetting your password.');
} else {
Session.set('resetPasswordToken', null);
}
});
} else {
template.find('#form-messages').html('Your password is too weak!');
}
return false;
}
});
}
I have already removed the insecure and autopublish options and I have published the userdata. I just cannot understand why template to change password does not work.
Well, the issue is you're running that code on the server with if (Meteor.isServer)
All your client code needs to be in if (Meteor.isClient) which is anything template level. You also get that for free if it's in a folder called client.