Issue Inserting MySQL Record With Node.js and Handlebars - mysql

I am having an issue when trying to submit a form with user information that inserts into a table. I have a userForm that allows user data to be entered with the following:
<form id="userForm">
<fieldset>
<legend>Add User</legend>
<p>First Name: <input id="fname" type="text" name="fname"/></p>
<p>Last Name: <input id="lname" type="text" name="lname"/></p>
<p>Email: <input id="email" type="text" name="email"/></p>
<p>Password: <input id="password" type="text" name="password"/></p>
</fieldset>
<input id="addUser" type="submit" name="add" value="Add User" onclick="addRow()" />
</form>
<script src="script.js"></script>
This then launches the following code in my script.js code:
function addRow(){
var form = document.getElementById("userForm");
var req = new XMLHttpRequest();
// Add the form data to the ajax request
var queryString = "";
var fname = form.fname.value;
var lname = form.lname.value;
var email = form.email.value;
var password = form.password.value;
queryString += "fname=" + fname + "&";
queryString += "lname=" + lname + "&";
queryString += "email=" + email + "&";
queryString += "password=" + password;
req.open('GET', '/insert-user?' + queryString, true);
req.send();
console.log(req.status);
Which executes the server side code:
app.get('/add-user', function(req,res){
var context = {};
res.render('addUser', context);
});
app.get('/insert-user',function(req,res,next){
var context = {};
pool.query("INSERT INTO user (`fname`, `lname`, `email`, `password`) VALUES (?,?,?,?)",
[req.query.fname, req.query.lname, req.query.email, req.query.password],
function(err, result){
if(err){
next(err);
return;
}
context.results = "Inserted id " + result.insertId;
res.render('exerciseTable',context);
});
});
The record is not being inserted into the table. When I console.log(req.status) I see 0 in the console. The add-user page is the form that the user fills out and then the insert-user code is called but it does not seem to be working. In fact, the URL does not change from http://18.219.103.143:3000/add-user to http://18.219.103.143:3000/insert-user? when I submit. It just stays static. It seems like my app.get('/insert-user'... code isn't even being called. Does anyone know what I am missing?
I am getting this error in the console:

Try to put
<form id="userForm" onsubmit="return false;">
Otherwise the default action on your form will be called. As your button is a submit button and that your default action is not set so it defaults to the same page and returning nothing or true will reload your page.

Related

Posting fetched data in database

I am trying to fetch user info through a form and then insert same data in the table 'orders'.
Everything looks correct, but there is an error showing total_cost is undefined.
I tried declaring it globally as well.
total_cost should be the quantity selected by the user in the form multiplied by the price of the product which is fetched from the database.
Here is the app.js post request:
// post create_order page
app.post("/create_order", function(req, res){
var name = req.body.name;
var quantity = req.body.quantity;
var email = req.body.email;
// fetching price from menu table
var sql = "select Price from menu where Name=?";
db.query(sql,[name], function(err, result){
if(err){
throw err;
}else if(result==0){
console.log("No items found!!!")
}else{
console.log(result)
console.log(Price)
var total_cost = result;
console.log(total_cost )
}
})
// Updating the order table
let today = new Date().toISOString().slice(0, 10);
let order = {
Item : name,
Quantity : quantity,
TotalCost : total_cost,
Date : today,
email : user
}
sql1 = "Insert into orders SET ?";
db.query(sql1, order, function(err, result2){
if(err){
throw err;
}else{
res.redirect("/orders");
}
})
})
Here is the corresponding order form used to fetch data:
<!-- //Order form goes here -->
<div class="orderform">
<form action="/create_order" method="POST">
<div class="form-group">
<label for="exampleFormControlSelect1">Select Item</label>
<select class="form-control" name="name" id="exampleFormControlSelect1">
<%result.forEach(function(result){%>
<option><%=result.Name%></option>
<%})%>
</select>
</div>
<div class="form-group" >
<label for="exampleFormControlInput1">quantity</label>
<input type="number" name="quantity" class="form-control" id="exampleFormControlInput1" placeholder="quantity" min="1" max="10">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Email address</label>
<input type="email" name="email" class="form-control" id="exampleFormControlInput1" placeholder="name#example.com">
</div>
Screenshot of error page:
Error page I am getting upon submitting the form
You defined your variable inner-scope; this will cause issues!
let profile = 20;
function call() {
console.log(profile); // == 20
let profile2 = 26;
}
call();
console.log(profile2); // undefined in other words your error.
If it's not a scope issue, then it's certainly the data you're grabbing from data-base is incorrect. Double check the query.

Google App Script doesn't set Bcc adress

I have develop a simple google app script to send an email with bcc I just trying to URL param To, From and subject is set is correctly but, the cc and bcc address are not set properly
My code snippet is here.
function doPost(e) { // change to doPost(e) if you are recieving POST data
var mailId = '';
var mailSubject = '';
var mailBody = '';
var htmlBody = '';
var senderName = '';
var replyToAddress = '';
var bccAddresses = '';
mailId = e.parameter['Email'];
mailSubject = e.parameter['Subject'];
mailBody = e.parameter['MailBody'];
htmlBody = e.parameter['HtmlBody'];
senderName = e.parameter['SenderName'];
replyToAddress = e.parameter['ReplyTo'];
bccAddresses = e.parameter['bccAddress'];
Logger.log(':::::::mailId:::::',mailId);
if(mailId != '' && mailId != null){
MailApp.sendEmail({
to:mailId,
subject:mailSubject,
htmlBody:mailBody,
bcc:bccAddresses,
name:senderName,
replyTo:replyToAddress,
});
}
var emailQuotaRemaining = MailApp.getRemainingDailyQuota();
return ContentService
.createTextOutput(emailQuotaRemaining);
}
function doGet(request) {
var emailQuotaRemaining = MailApp.getRemainingDailyQuota();
var result = {
available: 0
};
return ContentService.createTextOutput(
request.parameters.prefix + '(' + emailQuotaRemaining + ')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
My HTML code is
<form method="post" style="display:none;" id="form" action="https://script.google.com/macros/s/AKfycbwlMz27gP9vxZA-X58wvxgerhG46A6TEZw33YFe5mvJ0ejFSYQt/exec">
<input type="text" name="Subject" value="Test Subject" />
<input type="text" name="MailBody" value="Test Body" />
<input type="text" name="Email" value="subashc#softsquare.biz" />
<input type="text" name="SenderName" value="MSCB" />
<input type="text" name="ReplyTo" value="test#gmail.com" />
<input type="text" name="bccAddress" value="mscb39#yahoo.com" />
<textarea name="HtmlBody">Test Body</textarea>
<input type="submit" id="sub" />
</form>
<button onclick="subForm();">Submit</button>
<script>
function subForm() {
document.getElementById('form').submit();
}
</script>
Thanks in Advance,
Subash Chandrabose.M
Could you put BCC in the options and test.
MailApp.sendEmail(to, subject, "", {
htmlBody:mailBody,
bcc:bccAddresses,
name:senderName,
replyTo:replyToAddress
});
It seems as though you aren't refrencing a bcc adress when you are calling your function.. How are you calling your function?
(I would comment but I don't have enough reputation yet)

Validation from submitting in Apps Script

Please I need help. I have the same need of this post. I followed the instructions but I can't find my error. I'm frustratred.
When I submit with null fields, the script shows me a blank page.
When I submit with complete fields, the script shows me a blank page also and never upload the file.
This is my final code:
code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "NHD Papers";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName + ", Division: " + form.myDivision + ", School: " + form.mySchool + ", State: " + form.myState);
return "<h2>File uploaded successfully!</h2><p>Copy and paste the following URL into registration:<br /><br /><strong>" + file.getUrl() + '</strong></p>';
} catch (error) {
return error.toString();
}
}
form.html
<p>
<form id="myForm" onsubmit="validateForm();">
<h1>NHD Paper Upload</h1>
<label>Name</label>
<input type="text" name="myName" class="required" placeholder="Enter your full name..">
<label>Division</label>
<input type="text" name="myDivision" class="required" placeholder="(ex. Junior or Senior)">
<label>School</label>
<input type="text" name="mySchool" class="required" placeholder="Enter your school..">
<label>Affiliate</label>
<input type="text" name="myAffiliate" class="required" placeholder="Enter your affiliate..">
<label>Select file to upload. </label>
<input type="file" name="myFile">
<input type="submit" value="Submit File" >
<br />
</form>
</p>
<div id="output"></div>
<script>
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
this.value='Please be patient while your paper is uploading..';
var myFormObject = document.getElementById('myForm');
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(myFormObject);
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 15px; }
p {margin-left:20px;}
</style>
Regards,
In the IFRAME mode HTML forms are allowed to submit, but if the form has no action attribute it will submit to a blank page.
The solution suggested by the official documentation is to add the following JavaScript code to prevent all form submitions on load:
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
</script>
You can also add a return false; or event.preventDefault() at the end of your validateForm() function.

form getting redirected to base_url when action is set to null in codeigniter view

I submit the below form its processing the code in the controller but after processing its redirecting to my base url. Also I haven't used any redirect in my controller function. why is it redirecting to my base_url when the action is null?
This is my form code
<form action="" class="form-horizontal contact-1" role="form" method="post" id="contactform">
<input type="hidden" name="operation" value="newquery">
<div class="form-group">
<div class="col-sm-6">
<input type="text" class="form-control" name="name" id="name" placeholder="Name">
</div>
<div class="col-sm-6">
<input type="text" class="form-control" name="email" id="email" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input class="form-control" id="subject" type="text" name="subject" placeholder="Subject">
<textarea name="message" type="text" id="msg" class="form-control textarea" cols="30" rows="5" placeholder="Message"></textarea>
<button type="submit" id="contsub" class="btn btn-primary btn-block contact-1-button" data-loading-text="Sending" ><i class="fa fa-send"></i> Send Message</button>
</div>
</div>
</form>
and this is my ajax call
<script>
$(document).ready(function() {
$("#contsub").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var msg = $("#msg").val();
if (name == '' || email == '' || subject == '' || msg == '') {
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("contactform.php", {
name: name,
email: email,
subject: contact,
msg: msg
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
I am not able to figure out what the problem is?
1.If you set form action empty, form will be submitted to its current url.so look at your browser current url and I think it is same as your base_url.
2.If you click on the contsub button your javascript $("#contsub").click(function() will not execute perfectly because when you click this button it will submit the form too and will redirect to the action url.change your <button type="submit" to <button type="button" so it will not submit the form and your javascript will work.
<script>
$(document).ready(function() {
$("#contsub").click(function(e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var msg = $("#msg").val();
if (name == '' || email == '' || subject == '' || msg == '') {
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("contactform.php", {
name: name,
email: email,
subject: contact,
msg: msg
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
pressing the button causes the form to submit, redirecting you to your current location. adding the e.preventDefault(); will stop this from happening.

Twitter JSON API with jQuery

function getUsername()
{
var userName = document.form.screen_name.value;
document.getElementById("display").innerHTML = userName;
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
document.getElementById("display2").innerHTML = apiName;
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter.name);
$('#showdata').html("<p>item1="+twitter.follwers_count+" item2="+twitter.friends_count+"</p>");
});
});
Javascript code.
<form method="get" action="#" name="form">
Username: <input type="text" name="screen_name" id="username"/>
<input type="submit" value="submit" onclick="getUsername()" />
</form>
<p>Your username is <h2 id="display"></h2></p>
<p>Your api url is <h2 id="display2"></h2></p>
HTML Code
Whats wrong with this code? The alert comes back undefined.
Thanks
The data comes back as an array. You need to get the object at index 0:
function getUsername()
{
var userName = document.form.screen_name.value;
document.getElementById("display").innerHTML = userName;
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
document.getElementById("display2").innerHTML = apiName;
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter[0].name);
$('#showdata').html("<p>item1=" + twitter[0].follwers_count + " item2=" + twitter[0].friends_count + "</p>");
});
});
}
Of course, you could always just write twitter = twitter[0]; at the start of your function.
Oh, and here's your code jQuery-ified:
function getUsername()
{
var userName = $('[name=screen_name]').val();
$("#display").html(userName);
var apiName = "https://api.twitter.com/1/users/lookup.json?screen_name=" + userName + "&callback=?";
$("#display2").html(apiName);
$(document).ready(function(){
$.getJSON(apiName, function(twitter) {
alert(twitter[0].name);
$('#showdata').html("<p>item1=" + twitter[0].follwers_count + " item2=" + twitter[0].friends_count + "</p>");
});
});
}