I can't access a user input in node.js - javascript

I am developing an apt management app.
I managed to get all functions to work but I am having trouble with the last one.
Basically, user selects one of the 5 update options from the db update menu page by clicking one of the submit buttons numbered from 1 to 5.
Button#5 is for updating the monthly apt fee. User enters the new monthly fee and clicks the update button.
But no matter what I do, I can't access the user input in req.body.newFee.
When I display it at the console, node displays it as undefined. Can someone tell me what I am doing wrong?
Below is my main server.js file.
// Send login page file to the client.
app.get('/loginpg', function(req, res) {
res.sendFile("D:/Behrans-files/Web-projects/havuzlusite/loginpg.html");
});
app.post('/server', (req, res) => { //Post request to receive user login data that was posted to server.js by login form.
var usrname = req.body.isim;
var usrpwd = req.body.sifre;
if (usrname && usrpwd) { //Check if user has entered name and password in the login form.
if (usrname == 'Yonetim' && usrpwd == "admin") { //If building management name and pwd entered,
res.render('dbupdmenupg'); //Display db update menu page.
//Route to handle db update menu page.
app.post('/dbupdmenupg/:btnno', (req, res) => { // Get the number of clicked button.
console.log("newFee1: ", req.body.newFee);
// Route to handle apt fee payment - If button#1 was clicked.
if (req.params.btnno == 1) {
res.render('usrpmtpg'); //Display user apt fee payment page.
app.post('/', (req, res) => { //Post request to access payment month and payment amount inputs from user.
var usrname = req.body.usrname;
var pmtmnth = req.body.pmt_mnth;
var pmtamt = req.body.pmt_amt;
queryUsrName(usrname, function(response) { //Pass usrname and call function to see if the user is in db.
console.log('status_flg: ', response);
if (response == 'Found') { //If response has no error message, call function to update user payment data in db.
updateUsrPmtData(usrname, pmtmnth, pmtamt, function(response) { //Call function to update user apt fee payment data in db.
alert(response); //Display db update status message from called function.
res.render('usrpmtpg');
});
} else if (response == 'Not found')
alert('İsim veri tabanında bulunamadı. Ana sayfaya dönmek için lütfen Ana sayfa butonuna tıklayınız!'); //If response has error message, display error message.
else
alert('Site sakini ismi veri tabanında aranırken sorun oluştu.');
})
})
}
// Route to handle deletion of existing resident user - If button#2 was clicked.
if (req.params.btnno == 2) {
res.render('deluserpg');
app.post('/', (req,res) => {
var usrname = req.body.usrname;
queryUsrName(usrname, function(response) { //Pass usrname and call function to see if the user is in db.
if (response == 'Found') { //If response has no error message, it means user is in db, call function to delete it.
deleteUser(usrname, function(response) { // Pass username input data as parameter to call deleteuser function.
alert(response); //Display db delete status message from called function.
res.render('dbupdmenupg');
})
} else if (response == 'Not found') {
alert('İsim veri tabanında bulunamadı. Lütfen sistemde mevcut bir isim girin.'); //If response has error message, display error message.
res.render('deluserpg');
} else
alert('Site sakini ismi veri tabanında aranırken sorun oluştu.');
})
})
}
// Route to handle addition of new resident user - If button#3 was clicked.
if (req.params.btnno == 3) {
res.render("adduserpg");
app.post('/', (req,res) => {
var usrname = req.body.newname;
queryUsrName(usrname, function(response) { //Pass usrname and call function to see if the user is in db.
if (response == 'Found') {
alert('Isim veri tabaninda mevcut, tekrar eklenemez. Lütfen sistemde olmayan bir isim girin. '); //If response has error message, display error message.
} else {
//If response has error message, it means user is not in db, call function to add it.
addUser(req.body.newname, req.body.newpwd, req.body.newblokno, req.body.newdaireno, req.body.newaidat, function(response) { //Pass input data as parms to call addUser funcn.
alert(response);
})
}
res.render('adduserpg');
})
})
}
// Route to handle reseting residents for the new year - If button#4 was clicked.
if (req.params.btnno == 4) {
newyearReset(function(response) {
alert(response);
})
}
**// Route to handle updating apt monthly fee - If button#5 was clicked.
if (req.params.btnno == 5) {
res.render('updfeepg');
app.post('/updfeepg', (req,res) => {
newFee = req.body.newFee;
console.log("newFee: ", newFee);
if (newFee) {
aptfeeUpdate(newFee, function(response) {
alert(response);
})
}
})
res.end();**
// res.redirect("/dbupdmenupg");
}
})
} else { //If a resident user name and pwd entered, call function to query on name/pwd in database.
queryUsrNamePwd(usrname, usrpwd, function(rows) {
if (rows) { // If user name/pwd match db,
res.render('userdatapg', {rows}); // Display resident data.
} else
res.redirect('/loginpg');
})
}
} else //if no user name and pwd entered, display message
alert('Lütfen isim ve şifre giriniz!');
//res.end();
});
Below is the html form file updfeepg.html.
<body>
<! Create database update menu form >
<form class="updfee" action="/updfeepg" method="post">
<p class="parag" >Lütfen yeni aylık aidatı giriniz.<input type="number" class="newFee" id="newFee" max="999"></p>
<br>
<button type="submit" class="updfeebtn" name="updfeebtn" id="updfeebtn" >Aidatı güncelle</button>
<a href="http://localhost:3000" type="button" class='homepg-btn'>Ana sayfa</a>
</form>
</body>

You need to parse the body firstly before you could access it.
For that you can use multer.
UPD:
The issue is here
<input type="number" class="newFee" id="newFee" max="999">
You need to have name field here. The name field defines the name of that value in the body of the request.
Try this.
<input type="number" class="newFee" id="newFee" name="newFee" max="999">

Related

check if email exists in mongodb while typing

this project uses js , mongoose , node.js
if use an email that already exists during registration to create an account, it will refresh the page clear all fields and shows a pop up message using ajax that says email exists. i dont want the fields to be cleared
im trying to fix this. the idea that i thought would be perfect is if i can use an event listener that will check the email against the database every time the user types something in the email input field. i already did this with js to make sure the passwords are identical before posting, all help and tips and remarks are welcome
here is the part of the code that checks if email exists
module.exports.signUp = async (req, res) => {
const { site_web, username, fonction, direction, email} = req.body
try {
if(email){
var check = await InscritModel.findOne({ email: email });
if(check){
res.render('inscription', { layout: 'inscription', email: true});
}
else{
// create user
}
}
}
}
UPDATE
im still stuck with this, i trying to use ajax to constantly check the email input against the database in real time, but i know im messing up a lot of things,
i created a post route in user-routes called router.post("/emailCheck", emailCheck); and in function-controller file i created this function
module.exports.emailCheck = async (email) => {
var check = await InscritModel.findOne({ email: email });
if(check){
return 1;
}
else{
return 0;}
}
this is the html input call
<input type="email" id="txtUserEmail" class="form-control" name="email" placeholder="Email.." required>
and this is the crazy ajax code
$(document).ready(function () {
$('#txtUserEmail').keyup(function () {
var email = $(this).val();
if (email.length >= 3) {
$.ajax({
url: '/emailCheck',
method: 'post',
data: { email: email },
success: function (data) {
var divElement = $('#divOutput');
if (data) {
divElement.text(' already in use');
divElement.css('color', 'red');
}
else {
divElement.text( ' available')
divElement.css('color', 'green');
}
},
error: function (err) {
alert(err);
}
});
}
});
});
its shows a one very long error message with so many things, it ends with this
Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 8)
hopefuly ill get there, any help is appreciated, the idea i have in mind is to make ajax call a function that takes an email in its parameters and checks it against the database and returns true or false.
well, i ended up finding the solution, ill share for future people.
the goal: stop the other fields from getting cleared when the email already exists in database
the problem: verifying the email happens after the form is submit, which means the page gets refreshed
solution idea: disable the submit button, use js to listen on the email input, and verify the input against the database while the user is typing.
app.js or routes.js whatever u named it
const InscritModel = require('../models/inscrit-model');
router.get('/usercheck', function(req, res) {
console.log(req.query);
// dont forget to import the user model and change InscritModel by whatever you used
InscritModel.findOne({email: req.query.email} , function(err, InscritModel){
if(err) {
console.log(err);
}
var message;
if(InscritModel) {
console.log(InscritModel)
message = "user exists";
console.log(message)
} else {
message= "user doesn't exist";
console.log(message)
}
res.json({message: message});
});
});
in html
<div id="divOutput"></div>
<input type="email" id="usercheck" required>
<input type="submit" id="btsubmit" disabled />
in JS
$('#usercheck').on('keyup', function () {
console.log("ok");
console.log($(this).val().toLowerCase());
$.get('/usercheck?email=' + $(this).val().toLowerCase(), function (response) {
$('#divOutput').text(response.message);
var bouton = document.getElementById('btsubmit');
bouton.disabled = true;
if ($('#divOutput').html() === "user exists") {
$('#divOutput').text('Email not available').css('color', 'red');
}
else {
$('#divOutput').text('Email available').css('color', 'green');
bouton.disabled = false;
}
})
});

Trying to pass <%> HTML Variable to Javascript - Node, Passport, and Stripe

A bit of a newbie here. I've been looking for an answer that works and found some similarities in a Jade problem but I'm not using Jade. I have passed an "user" attribute into an HTML view as so:
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profilePage/profilePage.html', {
user : req.user // get the user out of session and pass to template
});
});
Then, in my profile HTML, I can access my user property like so:
<%=user.local.firstname%>'s Profile
However, I want to allow Stripe to send the user's credit card info via the Stripetoken. I have managed to include a variable amount from a text field the user inputs. However, I want to append the user property so I can use it in my callback. Here is the javascript/jquery that's included in the profile html:
<!-- New section -->
<script type="text/javascript">
<!-- Fill in your publishable key -->
Stripe.setPublishableKey('pkkey');
var stripeResponseHandler = function(status, response) {
var $form = $('#contactForm');
var $amount = $('#amount').val();
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.append($('<input type="hidden" name="amount" />').val($amount));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#contactForm').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
</script>
As you can see, I have managed to append the $amount variable so I can access it in the callback:
module.exports = function(app, passport) {
app.post('/stripe', function(req,res) {
// =====STRIPETOKEN======
var transaction = req.body;
var stripeToken = transaction.stripeToken;
var donationAmount = transaction.amount;
stripe.customers.create({
source : stripeToken,
account_balance : 0
},function(err, customer) {
if (err) {
console.log(err);
} else {
console.log("Success!");
}});
// ====CREATE CHARGE======
var charge =
{
amount : donationAmount,
currency : 'USD',
card : stripeToken
};
stripe.charges.create(charge, function(err, charge) {
if(err)
console.log(err);
else
{
res.json(charge);
console.log('Successful charge sent to Stripe!');
console.log(charge);
};
});
// ====PROFILE PAGE REDIRECT=====
res.render('profilePage/profilePage.html', {
});
});
So here's my problem. I want to pass the user's information, kind of like I did the amount, into the post method so when it redirects on success, I can pass it back in the res.render function, as well as send it to Stripe for description purposes. The only thing I can think of is to put the user info in a hidden field in HTML and access it like that, but that sounds messy and not proper.
This is my first time posting here so I apologize if it was too lengthy or not specific enough. Thanks!
The answer was in the way I was declaring passport and stripe in my application. Make sure you declare passport after everything to make the user variable available to stripe and all views.

How to print a response from Express.js into the POST requesting html page?

I wanted to print the login validation messages on the login page itself. But the response is being printed on a new blank page. Is there any way to fetch the response and print in on any existing div tags?
I'm using Express.js to handle the login validation.
app.post('/login',function(req,res){
var user_name=req.body.user;
var password=req.body.pwd;
console.log("User name = "+user_name+", password is "+password);
if (user_name=="sudheesh" && password=="pass") {
sess = req.session;
sess.user=user_name;
console.log("Logged in..");
res.send('done');
}
else {
res.send('not_done');
}
});
The HTML script looks like this,
<script>
$(document).ready(function(){
var user,pwd;
$("#submit").click(function(){
email=$("#user").val();
pass=$("#pwd").val();
/*
* Perform some validation here.
*/
$.post("http://localhost:3000/login",{user:user,pwd:pwd},function(data){
console.log(data);
if(data=='done')
{
alert("you have logged in..!");
window.location.href="/about";
}
});
});
});
</script>

JQuery not displaying HTML data from ajax response

Howdie do,
I have a form that simply takes a username and email from a user. The input is sanitiazed via client and on the server side.
The script is sending the POST with no issue and it's returning the data as it should be as I've checked in the log. However, for some reason, the data isn't being displayed in the browser.
Code is below and I feel it's a stupid item I'm overlooking, but I can't find it anywhere
<!DOCTYPE HTML>
<HEAD>
<TITLE>Jeremy's Form Submit Test </TITLE>
<script type="text/javascript" src="js/jquery-1.11.2.js"></script>
<script>
$(document).ready(function()
{
$("#FormSubmit").click(function() //Set click action on formsubmit button
{
var submit = true;
$('#MainForm input[type="text"]').each(function() //Loop through input fields to ensure data is present
{
if($.trim($('#User').val()) == '') //Remove whitespaces and check if field is empty
{
alert('Input can not be blank');
submit = false;
}
var regex = /^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$/; //RegEx to test email against
if(!regex.test($.trim($('#Email').val()))) //If supplied email without whitespaces doesn't match pattern, then alert user
{
alert('Please provide a valid email');
submit = false;
}
});
if(submit == true) //If data is present, then prepare email and user values to be submitted to .php page
{
data = {'user_name': $('#User').val(), 'email': $('#Email').val()}; //Add username and email to array
$.post("success.php", data, function(ReturnedData) //post data via ajx to success.php and retrieve response
{
console.log(JSON.stringify(ReturnedData));
if(ReturnedData.Type == 'Error') //If error returned, display error message
{
var results = '<h1>'+ReturnedData.Message+'</h1>';
}
else if(ReturnedData.Type == 'Success') //If success returned, display message and remove submit button
{
var results = '<h1>'+ReturnedData.Message+'</h1>';
$('#FormSubmit').remove();
}
$('div#DataHolder').html(results);
}, 'json');
}
});
});
</script>
</HEAD>
<BODY>
<form id="MainForm">
*UserName: <input type="text" id="User" name="FormUsername" required />
*Email: <input type="email" id="Email" name="FormEmail" required />
<input type="submit" id="FormSubmit" value="Submit">
</form>
<div id="DataHolder"></div>
</BODY>
</HTML>
The PHP file is below that returns a json_encoded response and I've confirmed via the console log that the data is being returned properly, but it's not displaying in the div I've set. The log file is showing the correct response, but it's not displaying:
{"Type":"Error","Message":"UserName must be at least 3 characters!!!"}
<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') //Check apache header to ensure its a json request
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "Naughty naughty. This wasn't an ajax request"));
die($ReturnedData);
}
if(isset($_POST)) //Ensure that POST is set
{
//Santiaze the post variables to be double sure no one is up to any funky business
$SaniUser = filter_var($_POST['user_name'],FILTER_SANITIZE_STRING);
$SaniEmail = filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);
//Check that username is at least 3 characters and return error if it's not
if(strlen($SaniUser) != 3)
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "UserName must be at least 3 characters!!!"));
die($ReturnedData);
}
//Check that email is a valid email
if(!filter_var($SaniEmail,FILTER_VALIDATE_EMAIL))
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "Please supply a valid email address!!!"));
die($ReturnedData);
}
//All variables are good. Return successfully message
$ReturnedData = json_encode(array("Type" => "Success", "Message" => "SUCCESS!!!" .$SaniUser. "Has successfully submitted the form"));
die($ReturnedData);
}
else
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "Naughty naughty. No data was submitted!!!"));
die($ReturnedData);
}
?>
WOWOWOW the issue was staring me right in the face.
I didn't initialize var results initially when the data is present. So when I called .html(results), the result variable scope was only in the if/else statement.
Setting the variable at the top of the if statement and then setting the returnedData to that value works
Updated code is below:
if(submit == true) //If data is present, then prepare email and user values to be submitted to .php page
{
var results;
data = {'user_name': $('#User').val(), 'email': $('#Email').val()}; //Add username and email to array
$.post("success.php", data, function(ReturnedData) //post data via ajx to success.php and retrieve response
{
console.log(JSON.stringify(ReturnedData));
if(ReturnedData.Type == 'Error') //If error returned, display error message
{
results = '<h1>'+ReturnedData.Message+'</h1>';
//alert(ReturnedData.Message);
}
else if(ReturnedData.Type == 'Success') //If success returned, display message and remove submit button
{
$('#FormSubmit').hide();
results = '<h1>'+ReturnedData.Message+'</h1>';
}
$('#DataHolder').html(results);
}, 'json');
}

Stripe error: The users credit card failed

I'm using Stripe to handle payments on my website. But, when I try to make a payment I'm getting a 'The users credit card failed' error. I've used this code on different sites and they work but, for some reason it isn't working here. Does anyone know what the problem might be? There definitely is money on the card:
function stripeResponseHandler(status, response)
{
if (response.error)
{
// Stripe.js failed to generate a token. The error message will explain why.
// Usually, it's because the customer mistyped their card info.
// You should customize this to present the message in a pretty manner:
alert(response.error.message);
}
else
{
// Stripe.js generated a token successfully. We're ready to charge the card!
var token = response.id;
var email = $("#email").val();
var price = $("#price").val();
var id = $("id").val();
// Make the call to the server-script to process the order.
// Pass the token and non-sensitive form information.
var request = $.ajax ({
type: "POST",
url: "pay.php",
dataType: "json",
data: {
"stripeToken" : token,
"email" : email,
"price" : price,
"id" : id
}
});
request.done(function(msg)
{
if (msg.result === 0)
{
// Customize this section to present a success message and display whatever
// should be displayed to the user.
window.location.replace("http://foo.com");
}
else
{
// The card was NOT charged successfully, but we interfaced with Stripe
// just fine. There's likely an issue with the user's credit card.
// Customize this section to present an error explanation
alert("The user's credit card failed.");
}
});
request.fail(function(jqXHR, textStatus)
{
// We failed to make the AJAX call to pay.php. Something's wrong on our end.
// This should not normally happen, but we need to handle it if it does.
alert("error");
});
}
}
function showErrorDialogWithMessage(message)
{
// For the tutorial, we'll just do an alert. You should customize this function to
// present "pretty" error messages on your page.
alert(message);
// Re-enable the order button so the user can try again
$('#buy-submit-button').removeAttr("disabled");
}
$(document).ready(function()
{
$('#buy-form').submit(function(event)
{
// immediately disable the submit button to prevent double submits
$('#buy-submit-button').attr("disabled", "disabled");
var fName = $('#first-name').val();
var lName = $('#last-name').val();
var email = $('#email').val();
var cardNumber = $('#card-number').val();
var cardCVC = $('#card-security-code').val();
// First and last name fields: make sure they're not blank
if (fName === "") {
showErrorDialogWithMessage("Please enter your first name.");
return;
}
if (lName === "") {
showErrorDialogWithMessage("Please enter your last name.");
return;
}
// Validate the email address:
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
showErrorDialogWithMessage("Please enter your email address.");
return;
} else if (!emailFilter.test(email)) {
showErrorDialogWithMessage("Your email address is not valid.");
return;
}
// Stripe will validate the card number and CVC for us, so just make sure they're not blank
if (cardNumber === "") {
showErrorDialogWithMessage("Please enter your card number.");
return;
}
if (cardCVC === "") {
showErrorDialogWithMessage("Please enter your card security code.");
return;
}
Stripe.createToken({
number: cardNumber,
cvc: cardCVC,
exp_month: $('#expiration-month').val(),
exp_year: $('#expiration-year').val()
}, stripeResponseHandler);
// Prevent the default submit action on the form
return false;
});
});
Thanks in advance

Categories

Resources