First of all I thank you for reading and making an attempt to my problem.
I dynamically rendered my {dropdown} but i was unable to get the selected value at my back-end.
on my form i am also getting photo and the name of suite is dynamically rendered.
Code below if i am doing something incorrect.
Lang - Javascript
FW - Express Js
Template - EJS
I have body-parse and set to true.
Issue i cannot get selected value to my back-end using POST request (undefined or null).
But if i use GET as the action & Request i do get the selected value.
Thank you again. If i am not clear please, i will explain clearly. I am newly NODE JS AND EXPRESS.
-Front-end
<form class="ui form" action="admin/uploadphoto" method="POST" enctype="multipart/form-data">
<h2 class=" ui dividing header" style="text-align: center;">Add Images to suites</h2>
<div class="two fields">
<div class="field">
<label>Add Suites Images</label>
<input name="suiteimage" type="file">
</div>
<div class="field">
<label>Suites*</label>
<select name="suiteselected" class="ui dropdown">
<% suites.forEach(function(suite) { %>
<option name = "suiteid" value="<%= suite.suite_name %>"><%= suite.suite_name %></option>
<% })%>
</select>
</div>
</div>
<input type="submit" class="ui button" tabindex="0" value="Save New Suite">
</form>
Back-end
const uuid = require("uuid/v4");
const { Pool } = require("pg");
const multer = require("multer");
// Insert photo and selected value from dropdown (options)
const PostPhoto = (req, res) => {
var suiteimage;
const suite_photo_id = uuid();
const {suiteselected} = req.body;
console.log( suiteselected + " --ID") //Here i am testing if selected valued is passed
// this is my multer function to config where i need to store my photo path
upload(req, res, err => {
suiteimage = req.file.path;
if (err) {
console.log(err);
} else {
console.log(suiteimage);
}
});
..... //my database query to save my post....
};
-route
router.post ('/uploadphoto', service.PostPhoto);
``
I have figured out the solution to this, body-parse should be required and extended true.
when having text and image as 1 form to be posted to the back-end make sure
Your image function (upload) is inside the req,res function or the values will be undefine or null.
if you need more explanation to comment.
//my post for image and text function
const PostPhoto = (req, res) => {
const suite_photo_id = uuid();
upload(req, res, function(err) {
const {suiteselected} = req.body;
console.log(req.file);
var imagePath = req.file.path.replace(/^public\//, '');
console.log( suiteselected + " --ID")
console.log(imagePath);
pool.query(
"INSERT INTO suite_photos (suite_photo_id,suite_photo,suite_id) VALUES($1,$2,$3)",
[suite_photo_id, imagePath,suiteselected],
(error, result) => {
if (error) {
throw error;
} else{
console.log(result);
res.redirect("/admin");
}
}
);
});
};
That's all that changed.
Thank you all!!!
Related
Im using a TMDB API to search for movies and add them to a watchlist.
In this javascript function im getting movie details based on user input and rendering the results to html using bootstrap.
const searchMovie = async (searchInput) => {
try {
axios.get(`https://api.themoviedb.org/3/search/movie?api_key={API_KEY}&language=en-US&query=${searchInput}&page=1&include_adult=false `)
.then((response) => {
console.log(response);
let movies = response.data.results;
let displayMovies = '';
$.each(movies, (index, movie) => {
displayMovies += `
<div class="col-md-3">
<div class="well text-center">
<img src="https://image.tmdb.org/t/p/original${movie.poster_path}">
<h5>${movie.title}</h5>
<h4>${movie.release_date}<h4>
<a class="btn btn-primary" href="#">Add to watchlist</a>
</div>
</div>
`;
});
$('#movies').html(displayMovies);
})
}catch(error) {
console.log(error)
}
}
I have another html file called watchlist.html that i want to send the movie selected from the search results to that file and build a watchlist.
Please try this one before stringify
var obj = JSON.parse(movie);
localStorage.setItem('selectedMovie', JSON.stringify(obj));
I am not sure how to submit data to my update form and what I have to put in the action field as the router.post has an :id. Below is my code:
router.post('/gymupdate/:id',async(req,res) => {
let gymName = req.body.firstname;
let location = req.body.city;
let phoneNumber = req.body.mobile;
let priceRange = req.body.price;
let id = req.params.id;
try{
check2(gymName,location,phoneNumber,priceRange);
if(!id) throw 'Pleaase provide an id';
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
if(checkForHexRegExp.test(id)===false) throw 'Not a valid objectid';
const updategym = await gymData.update(id,gymName,location,phoneNumber,priceRange)
if(updategym)
res.status(200).redirect('/gyms')
else {
res.status(500).render('gymbars/updategym', {title: "Error", error: 'Internal Server Error'})
}
}
catch(e){
res.status(400).render('gymbars/updategym', {title: "Error", error: e})
}
});
Form:
<form method="POST" action="/gyms/gymupdate/:id" id="signup-form" class="signup-form"></form>
The content in the action does not work, so how do I add id field to the action part similar to the router.post method?
This is how the user gets the id:
router.get('/gymupdate/:id',async(req,res) => {
const id = req.params.id;
const values = await gymData.getGym(id);
try{
if (req.session.user && req.session.user.role === 'owner'){
res.render('gymbars/updategym',{values:values})
}
else if(req.session.user && req.session.user!=='owner')
res.redirect('/login')
else{
res.redirect('/login')
}
}
catch(e){
res.sendStatus(500);
}
});
So the logic goes like, I display a list of gyms as links, once you click on them you get to the gym profile. There is a button there that says update this gym, once clicked it goes to the update gym page which is being talked about here.
if you are using any language for front end there is a way to write dynamic URL
but if you use pure HTML then this will help you
<form id="form_id" method="post" action="/aa">
<input type="submit">
</form>
<script>
document.getElementById("form_id").action = "/bbbbbb";
</script>
you need to bring your id
let id_to_pass//=get id which you want to pass in post api
document.getElementById("form_id").action = "/gymupdate/"+id_to_pass;
How can I receive the values of the radio buttons and a select list and put it on the file name?
This is the function that will be using the values :
router.get('/import', function(req, res, next) {
var csvStream = fastCsv()
.on('data', function(data) {
var report = new csvUploads({
jirakey: data[0],
status: data[1],
priority: data[2],
validity: data[3],
type: data[4],
month: data[5],
defectCategory: data[6],
defectSubCategory: data[7]
});
report.save(function(error) {
console.log(report);
if (error) {
throw error;
}
});
}).on('end', function() {});
const request = req.body;
let month = req.month;
let team = req.team;
const filename = month + ' - ' + team + '.csv';
console.log(res.send(filename));
const csvFilePath = "./uploads/" + filename;
var stream = fs.createReadStream(csvFilePath);
stream.pipe(csvStream);
res.json({
success: 'Data imported successfully',
status: 200
});
});
Currently this is what I have tried, it returns undefined in both the radio button and select list value
instead of
const request = req.body;
let month = req.month;
let team = req.team;
try
const request = req.body;
let month = request.month;
let team = request.team;
I would suggest that you simply serve the view (importer.html) and use it as as a client for your server (using POST), that way you may interact with the server and display the changes/retrieved data back in the client.
You will be needing :
GET route for displaying the "client".
POST route for using the "client submitted data and crafting an
adecuate response".
Client logic for doing something when the server replies.
Hope this proof-of-concept (working example) will help you understand better :
SERVER CODE
const express = require('express'); global.app = express()
const bodyParser = require('body-parser')
/* SETUP SERVER CONFIG OPTIONS */
const CONF = {
"htmlDir":__dirname+"/",
"port":3000
}
//----------------------------------------------------------
//.: Server StratUp : Setup Event Handling :.
function InitializeServer(){
console.log("[~] starting ...")
//:[EXPRESS]:MiddleWare
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
//:[EXPRESS]:Router (GET Requests)
app.get("/",RenderImport)
//:[EXPRESS]:Router (POST Requests)
app.post("/import",ImportRequest)
//:[EXPRESS]:Start
app.listen(CONF.port,onSuccessfullStartup)
}
/* Callback example for express successfully listening */
const onSuccessfullStartup=()=>{
console.log("[i] ready & listening","\n http://localhost:"+CONF.port+"/")
}
//----------------------------------------------------------
/* ROUTER EVENT FUNCTIONS : */
const RenderImport=(req,res)=>{res.sendFile(CONF.htmlDir+"importer.html")}
const ImportRequest=(req,res)=>{
console.log("[POST] /import")
console.log(req.body)
if(req.body.stringExample&&req.body.selectExample&&req.body.radioExample){
console.log(" > valid POSTData")
var doSomethingNow={"status":"OK","data":[1,2,3,4,5]}
res.json(doSomethingNow)
}else{
console.log(" > invalid POSTData")
res.json({"status":"ERROR"})
}
}
//----------------------------------------------------------
InitializeServer() // We can now start the server
CLIENT CODE (importer.html)
<html><head><title>INDEX</title></head><body>
<center>
<h1>SEND DATA TO SERVER</h1>
<form name="theForm">
<!-- String Example -->
<input name="stringExample" type="text"></input>
<!-- Select Example -->
<select name="selectExample">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<select>
<!-- Radio Example -->
<input type="radio" name="radioExample" value="a" checked> One
<input type="radio" name="radioExample" value="b" > Other
<input type="radio" name="radioExample" value="c" > Another
</form>
<button onclick="SEND()">SEND</button>
</center>
<script>
function SEND(){
var newXHR = new XMLHttpRequest();
newXHR.addEventListener("load",RequestDone);
newXHR.open("POST","/import");
newXHR.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
//Fetch Form Data
var form = document.theForm;
var inputx = form.elements["stringExample"];
var select = form.elements["selectExample"];
var radios = form.elements["radioExample"];
//Data for POST
var JSONObj = {}
JSONObj.stringExample = inputx.value
JSONObj.selectExample = select.value
JSONObj.radioExample = radios.value
console.log(JSONObj);
//Format Data for POST
var POSTData = JSON.stringify(JSONObj);
newXHR.send(POSTData);
}
function RequestDone(req){
var res = JSON.parse(req.target.response); console.log(res)
if(res.status=="OK"){alert("Succesfully Sent & Retrieved Data :\n"+res.data.toString())}
else if(res.status=="ERROR"){alert("The server received unexpected data or is missing important parameters")}
else{alert("Unexcpected Error!")}
}
</script>
</body></html>
I am trying to implement a simple search through firebase database. the logic is that
When A value is entered in the search box, go to database path of the entered value and get a snapshot value at the directory. for some reason, I have been stuck on this with the error listed below and I don't know what is causing it.
<form class="search" action="">
<input type="search" id="search-input" placeholder="Enter NSN number here..." required>
<button class="Init_search" id="findbutton">Search</button>
</form><br /><br />
the search result is displayed here
<div class="container"><br /><br />
<ul class="collapsible" data-collapsible="expandable" id="searchresult">
</ul>
</div>
this is my js code
document.getElementById("findbutton").addEventListener("click", function(e){
var FindNSN = document.getElementById('search-input').value;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
database = firebase.database();
var uid = firebase.auth().currentUser.uid;
console.log(FindNSN);
var searchref = database.ref('/Businesses/' + uid + '/Inventory/' + FindNSN);
searchref.on('value', search, errData); // this is dashboard.js:363
}
})
})
function search(data){
var container = document.getElementById('searchresult');
var uid = firebase.auth().currentUser.uid;
container.innerHTML = '';
data.forEach(function(SearchSnap) {
var key = SearchSnap.key;
var Results = SearchSnap.val();
console.log(Results);
var ResultCard = `
<li>
<div class="collapsible-header"><i class="mdi-navigation-chevron-right"></i><a name="987"/>${Results.ProductName}</a></div>
<div class="collapsible-body"><p>${Results.ProductDescription}</p></div>
</li>
`;
container.innerHTML += ResultCard;
})
}
this is the error I keep getting
Uncaught (in promise) Error: Query.on failed: Second argument must be a valid function.
at A (firebase-database.js:44)
at U.g.gc (firebase-database.js:170)
at firebase.auth.onAuthStateChanged (dashboard.js:363)
at firebase-auth.js:202
at <anonymous>
A # firebase-database.js:44
g.gc # firebase-database.js:170
firebase.auth.onAuthStateChanged # dashboard.js:363
(anonymous) # firebase-auth.js:202
the error is saying second argument is not a valid function. i was able to narrow it down the search() but i cant see what makes the function invalid.
What am I doing wrong and How can I fix it?
I am having this error I can't figure out how to fix;
TypeError: db.get is not a function
routes\boxes.js:20:25
server.js:45:5
database.js
module.exports = {
'url' : 'mongodb://localhost/database'
};
server.js
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var db = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(db.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'secretkeykeykeykey' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes/routes')(app, passport); // load our routes and pass in our app and fully configured passport
var boxes = require('./app/routes/boxes');
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/portal', boxes);
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
boxlist.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoxlistSchema = new Schema({
name: {
type: String
},
//insert your other key of collection
});
module.exports = mongoose.model('Boxlist', BoxlistSchema);
boxes.js
var express = require('express');
var router = express.Router();
var collection = require('./boxlist');
/*
* GET boxlist.
*/
router.get('/boxlist', function(req, res) {
var db = req.db;
var collection = db.get('boxlist');
collection.find({},{},function(e,docs){
res.json(docs);
});
});
/*
* POST to addbox.
*/
router.post('/addbox', function(req, res) {
var db = req.db;
// var collection = db.get('boxlist');
db.collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
/*
* DELETE to deletebox.
*/
router.delete('/deletebox/:id', function(req, res) {
var db = req.db;
var collection = db.get('boxlist');
var boxToDelete = req.params.id;
collection.remove({ '_id' : boxToDelete }, function(err) {
res.send((err === null) ? { msg: '' } : { msg:'error: ' + err });
});
});
module.exports = router;
global.js
// Boxlist data array for filling in info box
var boxListData = [];
// DOM Ready =============================================================
$(document).ready(function () {
// Populate the box table on initial page load
populateTable();
// Boxname link click
$('#boxList table tbody').on('click', 'td a.linkshowbox', showBoxInfo);
// Add Box button click
$('#btnAddBox').on('click', addBox);
// Delete Box link click
$('#boxList table tbody').on('click', 'td a.linkdeletebox', deleteBox);
});
// Functions =============================================================
// Fill table with data
function populateTable() {
// Empty content string
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON('/portal/boxlist', function (data) {
// Stick our box data array into a boxlist variable in the global object
boxListData = data;
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function () {
tableContent += '<tr>';
tableContent += '<td>' + this.boxname + '</td>';
tableContent += '<td>' + this.vm + '</td>';
tableContent += '<td>delete</td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#boxList table tbody').html(tableContent);
});
};
// Show Box Info
function showBoxInfo(event) {
// Prevent Link from Firing
event.preventDefault();
// Retrieve boxname from link rel attribute
var thisBoxName = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = boxListData.map(function (arrayItem) {
return arrayItem.boxname;
}).indexOf(thisBoxName);
// Get our Box Object
var thisBoxObject = boxListData[arrayPosition];
//Populate Info Box
$('#boxInfoName').text(thisBoxObject.fullname);
$('#boxInfoVm').text(thisBoxObject.vm);
$('#boxInfoDescription').text(thisBoxObject.description);
$('#boxInfoVersion').text(thisBoxObject.version);
};
// Add Box
function addBox(event) {
event.preventDefault();
// Super basic validation - increase errorCount variable if any fields are blank
var errorCount = 0;
$('#addBox input').each(function (index, val) {
if ($(this).val() === '') {
errorCount++;
}
});
// Check and make sure errorCount's still at zero
if (errorCount === 0) {
// If it is, compile all box info into one object
var newBox = {
'boxname': $('#addBox fieldset input#inputBoxName').val(),
'init': $('#addBox fieldset input#inputBoxInit').val(),
'vm': $('#addBox fieldset input#inputBoxVm').val(),
'description': $('#addBox fieldset input#inputBoxDescription').val(),
'version': $('#addBox fieldset input#inputBoxVersion').val()
}
// Use AJAX to post the object to our addbox service
$.ajax({
type: 'POST',
data: newBox,
url: '/portal/addbox',
dataType: 'JSON'
}).done(function (response) {
// Check for successful (blank) response
if (response.msg === '') {
// Clear the form inputs
$('#addBox fieldset input').val('');
// Update the table
populateTable();
} else {
// If something goes wrong, alert the error message that our service returned
alert('Error: ' + response.msg);
}
});
} else {
// If errorCount is more than 0, error out
alert('Please fill in all fields');
return false;
}
};
// Delete Box
function deleteBox(event) {
event.preventDefault();
// Pop up a confirmation dialog
var confirmation = confirm('Are you sure you want to delete this box?');
// Check and make sure the box confirmed
if (confirmation === true) {
// If they did, do our delete
$.ajax({
type: 'DELETE',
url: '/portal/deletebox/' + $(this).attr('rel')
}).done(function (response) {
// Check for a successful (blank) response
if (response.msg === '') {} else {
alert('Error: ' + response.msg);
}
// Update the table
populateTable();
});
} else {
// If they said no to the confirm, do nothing
return false;
}
};
portal.js
<!-- views/profile.ejs -->
<!doctype html>
<html>
<head>
<title>Vagrant CLI Node API</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<style>
body {
padding-top: 80px;
word-wrap: break-word;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="/javascripts/global.js"></script>
</head>
<body>
<div class="container">
<div class="page-header text-center">
<h1><span class="fa fa-th"></span> Portal</h1>
Profile
Logout
</div>
<div class="row">
<!-- AVAILABLE BOXES -->
<div class="col-sm-6">
<div id="boxList" class="well">
<h3><span class="fa fa-th"></span> Available Boxes</h3>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Vm</th>
<th>Delete</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<!-- BOX INFO -->
<div class="col-sm-6">
<div class="well" id="boxInfo">
<h3><span class="fa fa-th"></span> Box info</h3>
<p>
<strong>Select box name for more information</strong>
<br>
</p>
<p><strong>Name:</strong> <span id='boxInfoName'></span>
<br/><strong>Vm:</strong> <span id='boxInfoVm'></span>
<br/><strong>Description:</strong> <span id='boxInfoDescription'></span>
<br/><strong>Version:</strong> <span id='boxInfoVersion'></span></p>
<a class="fa fa-plus" href="#">
<i></i> start box instance and add to account</a>
</div>
</div>
<!-- ADD NEW BOX -->
<div class="col-sm-6">
<div class="well">
<h3><span class="fa fa-th"></span> Add box</h3>
<p>
<strong>Add new box to `available boxes`</strong>
<br>
</p>
<form id="addBox" class="form-inline" action="/portal/addbox" method="post">
<fieldset class="form-group">
<input id="inputBoxName" type="text" class="form-control" placeholder="Boxname" />
<input id="inputBoxInit" type="text" class="form-control" placeholder="Init" />
<input id="inputBoxVm" type="text" class="form-control" placeholder="Vm" />
<input id="inputBoxVersion" type="text" class="form-control" placeholder="Description" />
<input id="inputBoxDescription" type="text" class="form-control" placeholder="Version" />
<br>
<br>
<button type="submit" id="btnAddBox" class="btn btn-primary">Add Box</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Does anybody know what's going on and how to fix this? My code excludes node_modules link to dropbox
Thanks
PS. Parts of these codes are from this tutorial: link which can be forked from GitHub: link. This code works, but I've implemented it into my own application and as far as I know it's now the same code, but I get the error in my app, but not in his app.
Do one thing, remove db.get('boxlist');
Make a new file with the name boxlist
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoxlistSchema = new Schema({
name: {
type: String
},
//insert your other key of collection
});
module.exports = mongoose.model('Boxlist', BoxlistSchema);
In your boxes.js add
var collection = require('/boxlist');
now you can directly use queries,need not use var collection = db.get('boxlist');
Just delete this line from the code.
You have to define port number for accessing database.
Eg:
mongodb://localhost:27017/database
To fetch collection follow documentation https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html
var collection = db.collection('test');