Simple issue - I have a node express app that I want to perform a post request - using request passing the value of a string variable.
I don't want to transfer the name of the variable but its value.
If I just add the name to the query it will pass the actual name.
Looking forward for a solution.
Here is how your html file will look:
<form method='POST' action="/signup">
<b>USERNAME:</b> <input type="text" name="userName" placeholder="yourname">
<br>
<br>
<b>PASSWORD:</b> <input type="password" name="userPass" placeholder="***"><br>
<br>
<b>CONF. PASS.:</b> <input type="password" name="cnfPass" placeholder="***"><br>
<br>
<input type="submit" class = 'btn btn-primary' value="Signup">
</form>
Here is how your js file will look:
app.post('/signup',urlencodedparser,function(req,res){
var uPass=req.body.userPass;
var uName=req.body.userName;
var cnfPass = req.body.cnfPass;
if(uPass!=cnfPass)
res.end('Passwords dont match!')
else
{
con.query("INSERT INTO USERS(name,password) values (?,?)",[uName,uPass])
res.sendfile('user.html')
}
}
)
You can fetch the values of the variables by assigning name to them in the html file.
In this case,
I obtain the input name value with help of 'userName' and 'userPass' fields.
Related
I've been trying without success to make an update a form that contains multiple inputs for multiple images with Multer.
I managed to make the Create form, I used an upload.files({name: "image1", name: "image2}), etc. The thing is when I created the Update form and when I want to Edit a text field only I get an undefined error since no images files are found.
So I came up with an approach to save the previous (or current image) in and oldImage and assign this in case there is no imagen update.
Here is my code from the controller:
update: (req,res)=>{
let data_games3 = JSON.parse(fs.readFileSync(path.join(__dirname, '../baseDeDatos/data_games3.json')))
req.body.id = req.params.id
req.body.img_1 = req.files ? req.files.img_1[0].filename : req.body.oldImage1
req.body.img_2 = req.files ? req.files.img_2[0].filename : req.body.oldImage2
req.body.img_3 = req.files ? req.files.img_3[0].filename : req.body.oldImage3
req.body.img_4 = req.files ? req.files.img_4[0].filename : req.body.oldImage4
req.body.img_5 = req.files ? req.files.img_5[0].filename : req.body.oldImage5
let gamesUpdate = data_games3.map( games => {
if(games.id == req.body.id){
return games = req.body
}
return games
})
let gameActualizar = JSON.stringify(gamesUpdate, null, 2)
fs.writeFileSync(path.join(__dirname,'../baseDeDatos/data_games3.json'), gameActualizar);
res.redirect('/admin')
}
I can update an image only if the input receives an image. Here is my Edit View trying to store in the input name "oldImage1" a value with current img.
<form action="/admin/edit/<%= gameToEdit.id%>?_method=PUT" method="POST" enctype="multipart/form-data">
<input type="hidden" name="oldImage1" value="<%= gameToEdit.img_1%>" >
<input type="hidden" name="oldImage2" value="<%= gameToEdit.img_2%>" >
<input type="hidden" name="oldImage3" value="<%= gameToEdit.img_3%>" >
<input type="hidden" name="oldImage4" value="<%= gameToEdit.img_4%>" >
<input type="hidden" name="oldImage5" value="<%= gameToEdit.img_5%>" >
Im working with a JSON file as a DB.
The update works great but only if I update all the fields for images too.
In a view, i am trying to get the data that a user sent, via a form, from another view.
This is the view with the form (i have omitted some EJS stuff to avoid confusion):
<form action="/renderer" method="POST" id="sc-form">
<label for="model">Choose a model:</label>
<select name="model" id="model">
<% data.forEach(function(dat) { %>
<option value="<%= dat %>"> <%= dat %> </option>
<% }); %>
</select>
<input type="submit" value="Render the model!" />
</form>
As you can see, the user selects from a dropdown, and then data is POSTed on /renderer.
So, let's handle this POST request on routes.js:
app.post('/renderer', function(req, res) {
var myModel = req.body.model;
res.render('renderer.ejs', {data: myModel});
});
Pretty basic, we get the data that the form sent and we send it to renderer.ejs as parameters.
Finally, let's grab the data on /renderer.ejs (this is inside a <script> tag):
var modelName = <%- JSON.stringify(data) %>;
And i get this error:
data is not defined
But why is that? Data is the name of the variable that the router sent to the view, as parameter.
This is the third day that i am trying to make POST data appear on another view. If anyone could help i would really appreciate it.
I finally found this.
The form has to contain role="form", or else it wouldn't work.
I'm trying to test a POST method in a Nodejs/express application. I've connected to the firebase database.
My question is mainly related to the error. What am I doing wrong and how can I fix this please?
This is the error report:
PS C:\Users\WorkoutApp_v1> node app.js
Server started on port: 3000
Error: Reference.set failed: First argument contains undefined in property 'workouts.-Lqkqtcf6e2RED2F_1av.name'
This is the workout.js file with POST method.
const express = require('express');
const router = express.Router();
const firebase = require('firebase');
router.get('/add', function(req,res,next) {
res.render('workouts/add');
});
router.post('/add', function(req,res,next) {
var workout = {
name: req.body.name,
discription: req.body.discription,
set: req.body.set,
repsTime: req.body.repsTime
}
// console.log(workout);
// return;
// const fbRef = firebase.database().ref();
// var dbRef = fbRef.child('workouts');
// dbRef.push().set(workout);
// alternative implementation of the above 3-lines
firebase.database().ref().child('workouts').push().set(workout);
req.flash('success_msg', 'Workout saved');
res.redirect('/workouts');
});
module.exports = router;
This is the add.ejs file.
<form method="post" action="/workouts/add">
<div class="form-group">
<label>Exercise</label>
<input type="text" class="form-control" name="name" placeholder="Workout Name">
<label>Description</label>
<input type="text" class="form-control" name="description" placeholder="Description">
<label>Set</label>
<input type="text" class="form-control" name="sets" placeholder="Number of sets">
<label>RepsTime</label>
<input type="text" class="form-control" name="repsTime" placeholder="Number of repsTime">
</div>
<button type="submit" class="btn btn-default">Submit</button>
<a class="btn btn-danger" href="/workouts">Close</a>
</form>
The value undefined can't be written in RTDB.
The value undefined is what you get when you access object properties that don't exist.
Your req.body.name is undefined because req.body doesn't have a name property.
What does your commented-out console.log(workout) print?
When you write code that might lead to writing undefined in RTDB, you should replace it with something else. In this scenario, you could use req.body.name || '', to replace a missing name property with an empty string.
In general, using || can cause trouble, because values like 0 and '' are equivalent to false, so they would be replaced by your default value.
A safer thing to do is value === undefined ? defaultValue : value.
I have here a sample document from mongodb named chapters:
{_id:5c014c999cc48c3b0057988b, chapter_name:"AB"}
Controller: here is my function to get the chapters, and function to post to another db:
.controller('regCtrl', function($http, $location, $timeout, User, Bloodbankchapter) {
Bloodbankchapter.getBloodbankchapters().then(function(data) {
app.bloodbankchapters = data.data.bloodbankchapters;
});
this.regUser = function(regData) {
User.create(app.regData).then(function(data) {});
};
Then in my front-end to register:
<form name="regForm" ng-submit="register.regUser(regData); ">
<label>Chapter Name</label> <!--After I select the chapter name -->
<select ng-model="register.regData.branch" ng-options ="chapter._id as chapter.chapter_name for chapter in register.bloodbankchapters">
<option ng-repeat="chapter in register.bloodbankchapters" >{{chapter.chapter_name}}</option>
</select>
<label>Chapter ID</label> <!--chapter ID will appear here-->
<input type="text" ng-model="register.regData.branch_id" hidden>
<label>Chapter name</label> <!--How to make chapter name appear here?-->
<input type="text" ng-model="register.regData.branch_name" hidden>
<button ng-disabled="register.disabled" type="submit">Submit</button>
</form>
My problem here is after I selected the chapter name the second input was correct and it post the id into the db, but how can I get the chapter.name and post it to db?
I tried getting the text value from the select box and then appending it to a textbox like here: http://jsfiddle.net/kxqJN/, but when I register, the object id is being registered instead of chapter_name like this:
`{branch_id:5c014c999cc48c3b0057988b, branch_name:"5c014c999cc48c3b0057988b"}`
How can I display the name in the first box and the id in the second?
I bet you haven't tried what i suggested in the comments: chapter.chapter_name for chapter in register.bloodbankchapters track by chapter._id will lead you to have both values in your model:
angular.module('selectExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.register = {
regData: {
branch: {},
},
bloodbankchapters: [
{_id:'5c014c999cc48c3b0057988b', chapter_name:"AB"},
{_id:'5c014c999cc48c3b0057988c', chapter_name:"A"},
],
};
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="selectExample" ng-controller="ExampleController">
<select ng-model="register.regData.branch" ng-options ="chapter.chapter_name for chapter in register.bloodbankchapters track by chapter._id">
<option ng-repeat="chapter in register.bloodbankchapters" >{{chapter.chapter_name}}</option>
</select>
<div>{{register.regData.branch}}</div>
</div>
Try this way, you will get selected chapter object inside register.regData.branch
<select ng-model="register.regData.branch" ng-options ="chapter as chapter.value for chapter in register.bloodbankchapters">
Hi I hope someone can help on the client details page I need to hide the Email forwarding button and the DNS management button if the client has selected custom nameservers. I just can't work it out son any help is much welcomed ..Here is the code that takes the input;
<form method="post" action="{$smarty.server.PHP_SELF}?action=domaindetails">
<input type="hidden" name="sub" value="savens">
<input type="hidden" name="id" value="{$domainid}">
<p><input type="radio" name="nschoice" value="default" id="nschoicedefault" onclick="usedefaultns()"{if $defaultns} checked{/if} /> <label for="nschoicedefault">{$LANG.nschoicedefault}</label><br />
<input type="radio" name="nschoice" value="custom" id="nschoicecustom" onclick="usecustomns()"{if !$defaultns} checked{/if} /> <label for="nschoicecustom">{$LANG.nschoicecustom}</label></p>
And here is the code for the buttons;
{if $emailforwarding}
<td><form method="post" action="{$smarty.server.PHP_SELF}?action=domainemailforwarding">
<input type="hidden" name="domainid" value="{$domainid}">
<p align="center">
<input type="submit" value="{$LANG.domainemailforwarding}" class="button">}
</p>
</form></td>
{/if}
{if $dnsmanagement}
<td><form method="post" action="{$smarty.server.PHP_SELF}?action=domaindns">
<input type="hidden" name="domainid" value="{$domainid}">
<p align="center">
{<input type="submit" value="{$LANG.domaindnsmanagement}" class="button">}
</p>
</form></td>
{/if}
I suggest writing a helper function and calling it at the top of the tpl file
and passing the domain id to it.
You can then use the WHMCS internal API function Domain Nameservers to get the domains nameservers then compare them against the default nameservers in the tblconfiguration in the WHMCS database.
Something like this
{php}
// include our helper php file
require_once(dirname(__FILE__).'/Helper.php');
//get domain id from our template variables
$domainid = $this->get_template_vars('domainid');
//call to our helper function passing the domain ID
$hasCustomeNameServers = Helper::hasCustomNameServers($domainid);
//Once we've compared the nameservers agains the default ones we write
//our binary check to the template
if($hasCustomeNameServers >0){
$this->assign('hasCustomeNameServers',true);}
{/php}
Then in side our Helper.php we have something like the following
<?php
class Helper {
public static function hasCustomNameServers($domainid) {
$isCustom = 0;
//Interal API call to get the domains nameservers
$command = "domaingetnameservers";
$adminuser = "admin";
$values["domainid"] = $domainid;
$results = localAPI($command,$values,$adminuser);
//get default nameservers
$defautName1 ='';
$sql = mysql_query('SELECT value FROM tblconfiguration '.
' WHERE setting = "DefaultNameserver1"');
if ($res = mysql_fetch_assoc($sql)) {
$defautName1 = $res["value"];}
$defautName2 ='';
$sql = mysql_query('SELECT value FROM tblconfiguration '.
' WHERE setting = "DefaultNameserver2"');
if ($res = mysql_fetch_assoc($sql)) {
$defautName2 = $res["value"];}
//compare results
foreach ($results as &$value) {
if($value == $defautName1 || $value == $defautName2){
$isCustom++;
}
}
return $isCustom;
}
}
Now it's simply a matter on the template to wrap the {if $emailforwarding} and the {if $dnsmanagement} blocks around our check {if !hasCustomeNameServers}
I hope this helps you in the right direction this is by no means a comprehensive answer but is a guide towards the approach I think you should take in implementing your solution.