Posting fetched data in database - html

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.

Related

Why can't my Nodejs application cannot see my sqlite3 database column?

There are not errors associated with database or table, but it is not seeing the columns. This is the error:
Node server is running..
SQLITE_ERROR: no such column: scene
This is the table:
CREATE TABLE animalStream (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cascade_name TEXT NOT NULL,
enclosre_name TEXT NOT NULL,
scene TEXT NOT NULL,
sensorCamAddress TEXT NOT NULL,
streamerCamAddress TEXT NOT NULL,
duration INTEGER NOT NULL
);
The Nodejs code below allows me to receive data from the HTML form
const path=require('path');
const sqlite3 = require("sqlite3").verbose();
const db_name = path.join(__dirname, "wildlife.db");
const db = new sqlite3.Database(db_name);
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
res.sendFile('/home/harry/interface/in9.html');
});
app.post('/submit-student-data', function (req, res) {
var scene = req.body.scene
var cascade_name = req.body.cascade_name;
var enclosre_name = req.body.enclosre_name;
var sensorCamAddress = req.body.sensorCamAddress
var streamerCamAddress = req.body.streamerCamAddress
var duration = req.body.duration;
db.run(`INSERT INTO animalStream(scene) VALUES(scene)`, ['C'], function(err) {
if (err) {
return console.log(err.message);
}
// get the last insert id
console.log(`A row has been inserted with rowid ${this.lastID}`);
});
});/////////////////
var server = app.listen(3000, function () {
console.log('Node server is running..');
});
<!DOCTYPE html>
<html><body style="background-color:black;"><blockquote><blockquote>
<form action="/submit-student-data" method="post">
<p style="color:white;">Cascade file name:<br>
<input type = "text" name = "cascade_name" /></p>
<p style="color:white;">Enclosure name:<br>
<input type = "text" name = "enclosre_name" /></p>
<p style="color:white;">Scene number:<br>
<input type = "text" name = "scene" /></p>
<p style="color:white;">Sensor Camera IP address:
<br> <input type = "text" name = "sensorCamAddress" /></p>
>
<p style="color:white;">Streamer Camera IP address:
<br> <input type = "text" name = "streamerCamAddress" /></p>
<p style="color:white;">Scene duration:
<br><input type = "text" name = "duration" /></p>
<br>
<center> <INPUT type="submit" value="Send"> <INPUT type="reset"></center>
</form>
</blockquote></blockquote>
</body></html>
As I mentioned, it seems to pick up the database and table fine. It just doesn't see the columns for some reason. I would appreciate any input.
I think you must write your query like this:
`INSERT INTO animalStream (scene) VALUES("${scene}")`
and also you didn't set any value to other column that set NOT NULL

How to remove attr 'select' from dropdown list options that is repopulate with ajax request

I made a form that has a chained dropdown lists. Each subsequent dropdown list will be repopulated with ajax request based on the first dropdown list selection. In each dropdown list the first selected field is "---------" which has the attribution selected. When user selects another option the previous selected option still has the attribute of "selected". What I want to achieve is that the new selected option will be the one which has the selected attribute.
I have tried the .removeProp('selected', false)
and .removeAttr('selected') but the problem is persisting.
Here is the HTML Code:
<div id="div_id_CommonForm-country" class="form-group">
<label for="id_CommonForm-country" class=" requiredField">
country :
<span class="asteriskField">*</span>
</label>
<div class="">
<select name="CommonForm-country" class="select form-control" required="" id="id_CommonForm-country">
<option value="" selected="">---------</option>
<option value="1">USA </option>
<option value="5">Canada</option>
</select>
</div>
Here is the ajax request:
<script type="text/javascript">
$("#id_CommonForm-country").change(function(){
var url_province = $("#ads_main_post_form").attr("data-provinces-url"); // get the url of the `load_provinces` view
var countryId = $(this).val(); // get the selected country ID from the HTML input
$("#id_CommonForm-country option:selected").each(function () {
$(this).attr('selected', '');
});
var value = $(this).val();
$(this).find('option[value="'+value+'"]').attr("selected", "selected");
$.ajax({ // initialize an AJAX request
url: url_province, // set the url of the request (= localhost:8000/twons/ajax/load-rovinces/)
data: {
'user_country': countryId, // add the country id to the GET parameters
csrfmiddlewaretoken: '{{csrf_token}}',
},
success: function (data) { // `data` is the return of the `load_provinces` view function
var json = JSON.parse(data);
var provinces_list = $("#id_CommonForm-province").html('');
var city_list = $("#id_CommonForm-city").html('');
city_list.append('<option selected disabled>'+'---------'+ '</option>');
var first_item =
'<option selected disabled>'+'---------'+ '</option>';
var list=""
for(var j = 0; j < json.province_id.length; j++) {
list+=
'<option value="'+json.province_id[j]+'">'+json.province_name[j]+'</option>';
// replace the contents of the province input with the data that came from the server
}
complete_list = first_item.concat(list);
provinces_list.append(complete_list);
}
});
});
Any help or suggestion is highly appreciated:
Note: I have tried many suggested solutions posted on stackover flow but nothing helpt.
You can simply use removeAttr('selected'); to remove selected and then use attr("selected", "selected"); to add option selected to only to choosen option.
Demo code :
$("#id_CommonForm-country").change(function() {
var url_province = $("#ads_main_post_form").attr("data-provinces-url");
var countryId = $(this).val();
$("#id_CommonForm-country option").removeAttr('selected'); //remove attr selected
$(this).find('option[value="' + countryId + '"]').attr("selected", "selected"); //add selected to option actual selected
console.log(countryId)
//your ajax call
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_id_CommonForm-country" class="form-group">
<label for="id_CommonForm-country" class=" requiredField">
country :
<span class="asteriskField">*</span>
</label>
<div class="">
<select name="CommonForm-country" class="select form-control" required="" id="id_CommonForm-country">
<option value="" selected>---------</option>
<option value="1">USA </option>
<option value="5">Canada</option>
</select>
</div>

Knockout foreach generate html fields

I want to display as many fields as user wants.
Maybe you have idea how can I do this case using foreach loop in Knockout framework.
For example numberOfFields is input field where user can enter how many fields he wants to display
<input id="numberOfFields" type="text" data-bind="value: obj().numberOfFields() />
<div data-bind="foreach: new Array(obj().numberofCashFlows())">
<label for="quantity$index()">Flow number $index()</label>
<input id="quantity$index()" type="text" data-bind="value: quantityArray[$index()]" />
</div>
Of course code doesn't work, I want to tell you what I mean.
If user enters 3 I want to show 3 labels and inputs with id quantity1, quantity2, quantity3 and with values: quantityArray[0], quantityArray[1], quantityArray[2]
Can you help me or give some advice?
If I got your question right, this should be it by approx. I've also added and observable to the Quantity to show you how you could expand on the example with bound properties.
console.clear();
function Quantity(id, label) {
var self = this;
self.id = id;
self.label = ko.observable(label);
};
ko.applyBindings(() => {
var self = this;
self.amount = ko.observable(0);
self.quantity = ko.observableArray([]);
self.amount.subscribe(function(amount) {
var quantity = self.quantity().length;
amount = Number(amount);
if (amount > quantity) {
for (var i = quantity; i < amount; i++) {
self.quantity.push(new Quantity(i+1, 'label for ' + (i+1)));
}
} else if (amount < quantity) {
var minus = quantity - amount;
for (var i = 0; i < minus; i++) {
self.quantity.pop();
}
}
});
self.amount(2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<label>amount: </label>
<input type="number" data-bind="textInput: amount" min="0" />
<div data-bind="foreach: quantity">
<input type="text" data-bind="textInput: label, attr: { placeholder: 'label for ' + id }" /><span data-bind="text: label"></span><br />
</div>

Issue Inserting MySQL Record With Node.js and Handlebars

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.

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.