Why wont this code run if it's inside a function? - javascript

Here's my code that does work:
firebase.initializeApp({});
var auth = firebase.auth();
const firestore = firebase.firestore();
const settings = {timestampsInSnapshots: true};
firestore.settings(settings);
var db = firebase.firestore();
$(function() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var uid = user.uid;
// code in question
db.collection('users').doc(uid).collection('people').doc().set({
firstname: "John",
lastname: "Doe"
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
} else {
// User is signed out.
}
});
});
However, I want to trigger the db.collection bit after a form on the page is submitted; something like this:
firebase.initializeApp({});
var auth = firebase.auth();
const firestore = firebase.firestore();
const settings = {timestampsInSnapshots: true};
firestore.settings(settings);
var db = firebase.firestore();
$(function() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var uid = user.uid;
$('#myform').on('submit', function() {
db.collection('users').doc(uid).collection('people').doc().set({
firstname: "John",
lastname: "Doe"
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
});
} else {
// User is signed out.
}
});
});
But for whatever reason that won't work.
Edit: Here's the entire #myform. This exists inside a bootstrap modal
<form id="myform">
<div class="form-row">
<div class="col-md-12">
<label for="firstname">First Name</label>
<div class="input-group">
<span class="input-group-addon"><i class="icofont icofont-user"></i></span>
<input type="text" class="form-control" id="firstname" required>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-12">
<label for="lastname">Last Name</label>
<div class="input-group">
<span class="input-group-addon"><i class="icofont icofont-user"></i></span>
<input type="text" class="form-control" id="lastname" required>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-12">
<label for="email">Email</label>
<div class="input-group">
<span class="input-group-addon"><i class="icofont icofont-email"></i></span>
<input type="email" class="form-control" id="email" required>
</div>
<div id="email-error"></div>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-3">
<label for="phone">Phone</label>
<div class="input-group">
<span class="input-group-addon"><i class="icofont icofont-phone"></i></span>
<input type="tel" class="form-control" id="phone">
</div>
<div id="phone-error"></div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="btn-add-person">Add Person</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</form>

Your form submission is probably making the page reload. Try sticking onsubmit="return false;" in the attrs of your <form>.

Related

Stripe implementation in my own form in an Express app

I'm trying to get some value(total = total + itemJson.price * item.quantity) into my own form for stripe.
Every time I try to submit I get this error message:
"$ node server.js
C:\Users\Marcio\dsdrucker1\server.js:44 req.body.items.forEach(function(item) {
^
TypeError: Cannot read property 'forEach' of undefined
at C:\Users\Marcio\dsdrucker1\server.js:44:22
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)".
Here below you can find my code I have written. What am I doing wrong?
app.post('/checkout', function(req, res) {
fs.readFile('items.json', function(error, data) {
if (error) {
res.status(500).end()
} else {
const itemsJson = JSON.parse(data)
const itemsArray = itemsJson.roupa
let total = 0
req.body.items.forEach(function(item) {
const itemJson = itemsArray.find(function(i) {
return i.id == item.id
})
total = total + itemJson.price * item.quantity
})
stripe.charges.create({
amount: total,
source: req.body.stripeTokenId,
currency: 'usd'
}).then(function() {
console.log('Charge Successful')
res.json({ message: 'Successfully purchased items' })
}).catch(function() {
console.log('Charge Fail')
res.status(500).end()
})
}
})
})
<div class="col-sm-6 col-md-4 col-md-offset-4 col-sm-offset-3">
<h1>Checkout</h1>
<h4>Your Total: ${{total}}</h4>
<div id="charge-error" class="alert alert-danger {{#if noError}}hidden{{/if}}">
{{errMsg}}
</div>
<form action="/checkout" method="post" id="checkout-form">
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" required name="name">
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<label for="address">Address</label>
<input type="text" id="address" class="form-control" required name="address">
</div>
</div>
<hr>
<div class="col-xs-12">
<div class="form-group">
<label for="card-name">Card Holder Name</label>
<input type="text" id="card-name" class="form-control" required>
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<label for="card-number">Credit Card Number</label>
<input type="text" id="card-number" class="form-control" required>
</div>
</div>
<div class="col-xs-12">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="card-expiry-month">Expiration Month</label>
<input type="text" id="card-expiry-month" class="form-control" required>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="card-expiry-year">Expiration Year</label>
<input type="text" id="card-expiry-year" class="form-control" required>
</div>
</div>
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<label for="card-cvc">CVC</label>
<input type="text" id="card-cvc" class="form-control" required>
</div>
</div>
</div>
<button type="submit" class="btn btn-success">Buy now</button>
</form>
</div>
</div>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript" src="checkout.js"></script>
This is the Js I used for my form
Stripe.setPublishableKey('pk_test_BDlJ33LBsh5s6L69P5y3AAvp00ETkWe6tP');
var $form = $('#checkout-form');
$form.submit(function (event) {
$('#charge-error').addClass('hidden');
$form.find('button').prop('disabled', true);
Stripe.card.createToken({
number: $('#card-number').val(),
cvc: $('#card-cvc').val(),
exp_month: $('#card-expiry-month').val(),
exp_year: $('#card-expiry-year').val(),
name: $('#card-name').val()
}, stripeResponseHandler);
return false;
});
function stripeResponseHandler(status, response) {
if (response.error) { // Problem!
// Show the errors on the form
$('#charge-error').text(response.error.message);
$('#charge-error').removeClass('hidden');
$form.find('button').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
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));
// Submit the form:
$form.get(0).submit();
}
}

req.session.flash = { } not working sails.js

I'm really new at sails.js and at the moment I'm using sails 1.0 . I've got the problem when I try to validate my signup page that the once the form is invalid the error message is shown above the form as expected but when I do the refresh it is still there. Beside that everything is okay.
Routing is done manually and I think the problem is here req.session.flash = {}; in api/controllers/UsersController.js which is not being empty object !!
api/controllers/UsersControllers.js
module.exports = {
signup:function(req,res,next){
res.locals.flash = _.clone(req.session.flash);
res.view('pages/signup');
req.session.flash = {};
},
create:function(req,res,next){
var values = req.allParams();
Users.create(values).exec(function(err,user){
// if there's an error
if(err){
console.log(err);
req.session.flash = {
err: err
}
// if error redirect back to signup page
return res.redirect('/users/signup');
}
// After successfully creating the user
// redirect to the show action
res.view('pages/create');
req.session.flash = {};
});
}
};
view/pages/signup.ejs
<div class="container">
<% if(flash) { %>
<ul class="alert alert-success">
<% Object.keys(flash.err).forEach(function(error){ %>
<li> <%- JSON.stringify(flash.err[error]) %> </li>
<% }) %>
</ul>
<% } %>
<div class="row login-pannel">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading login-pannel-heading">
<h3 class="panel-title"> User Signup </h3>
</div>
<div class="panel-body login-pannel-body">
<form class="login-form" method="post" action="/users/create">
<div class="form-group">
<label for="loginUsername">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Your Name" autofocus>
</div>
<div class="form-group">
<label for="loginUsername">Email address</label>
<input type="email" class="form-control" id="loginEmail" name="email" aria-describedby="emailHelp" placeholder="Your Email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="loginPassword">Password</label>
<input type="password" class="form-control" id="pass" name="password" placeholder="Password">
<label class="text-danger" id="signup-pass"></label>
</div>
<div class="form-group">
<label for="loginPassword">Confirm Password</label>
<input type="password" class="form-control" id="con-pass" name="conPassword" placeholder="Confirm Password">
<label class="text-danger" id="signup-con-pass"></label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-danger reset-button">Reset</button>
<input type='hidden' name='_csrf' value='<%= _csrf %>'>
</form>
</div>
</div>
</div>
</div>
</div>
If my memory does not betray me, you must make any changes to your session object before sending the response. In your api/controllers/UsersControllers.js try to swap these two lines:
res.view('pages/create');
req.session.flash = {};
It should be:
req.session.flash = {};
res.view('pages/create');
Read more about sessions here. The most important thing there:
The property will not be stored in the session store nor available to
other requests until the response is sent.

Javascript fail to redirect after firebase authentication

I'm authenticating users registered in my firebase database and i want to redirect the user after successful authentication
const txtEmail = document.getElementById('email');
const txtPass = document.getElementById('password');
const loginBtn= document.getElementById('reg');
loginBtn.addEventListener('click', e => {
const mail = txtEmail.value;
const pass = txtPass.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(mail, pass);
if(promise){
window.location = "{{ route('users') }}";
console.log("{{ route('users') }}");
}else{
}
});
the log is successfully printed but the redirection fails may someone help
this is my form i don't know but maybe there is something wrong in it
<form class="form-horizontal m-t-20" method="post">
{{ csrf_field() }}
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" type="text" required="" id="email" placeholder="email">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" type="password" id="password" required="" name="password" placeholder="Password">
</div>
</div>
<div class="form-group ">
<div class="col-xs-12">
<div class="checkbox checkbox-custom">
<input id="checkbox-signup" type="checkbox">
<label for="checkbox-signup">
Remember me
</label>
</div>
</div>
</div>
<div class="form-group text-center m-t-30">
<div class="col-xs-12">
<button class="btn btn-custom btn-bordred btn-block waves-effect waves-light" class="reg" id="reg">
Login
</button>
</div>
</div>
<div class="form-group m-t-30 m-b-0">
<div class="col-sm-12">
<i class="fa fa-lock m-r-5"></i> Forgot your password?
</div>
</div>
</form>

Cannot /Post - Login Authentication

I am creating an app and I need a SignIn / SignUp functionality for the same. Here is my SignIn HTML:
<div style="padding-top:30px" class="panel-body" >
<div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>
<form action="verifySignin" method="post" id="verifySignin" class="form-horizontal" role="form">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="login-username" type="text" class="form-control" name="username" value="" placeholder="username" required="" autofocus="" >
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="login-password" type="password" class="form-control" name="password" placeholder="password">
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<button class="btn btn-md btn-primary btn-block" type="submit">Login</button>
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div style="border-top: 1px solid#888; padding-top:15px; font-size:85%" > Don't have an account?
<a href="#" onClick="$('#loginbox').hide(); $('#signupbox').show()">
Sign Up Here
</a>
</div>
</div>
</div>
</form>
</div>
My app.js has the following to route:
app.post('/verifySignin', home.verifySignin);
app.get('/verifySignin', home.verifySignin);
Under routes folder> I have created a home.js file which contains the following:
function verifySignin(req,res)
{
req.session.name=req.param("username");
var password = req.param("password");
console.log("session name:"+req.session.name);
var verifyUserQuery="select username, password from Users where Username='"+req.param("username")+"' and Password = '"+req.param("password")+"'";
mysql.fetchData(function(err,results){
if(err){
throw err;
}
else
{
if(results.username==req.param("username") && results.password == password){
res.render('kanban', { name: req.param("username") });}
else {
res.render('ErrorPage');
}
}
},verifyUserQuery);
}
exports.verifySignin=verifySignin;
When I click on the Login button, I get the error : Cannot POST /verifySignin.
Any help would really be appreciated. Thanks.
Try to use it like,
var users = require('./home/users');
in addition, this is a very bad practice due to security concerns
"select username, password from Users where Username='"+req.param("username")+"' and Password = '"+req.param("password")+"'"
pass values as parameters or bind them.

How to stop event propagation in AngularJS

When i am clicking on the "Sign Up" button, it is also going to the handler of "login" button. I have used $event.stopPropagation() for "Sign Up" button to avoid it, but it is not working.
The code -
<form role="form" ng-submit="login(userName, password)" class="form-horizontal">
<div class="form-group">
<label for="usrNm" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="email" id="usrNm" ng-model="userName" class="form-control input-lg" placeholder="Enter email"/>
</div>
</div>
<div class="form-group">
<label for="pwd" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" id="pwd" ng-model="password" class="form-control input-lg" placeholder="Password"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-default">LOGIN</button>
<button class="btn" ng-click="register(); $event.stopPropagation();">SIGN UP</button>
</div>
</div>
</form>
controller.js -
expmodule.controller('loginForm', function($scope, sharedProperties) {
var auth;
$scope.login = function (userid, password) {
auth = sharedProperties.session.isAuthenticated(userid, password);
if (auth) {
alert("Welcome "+userid);
window.location = "home.html";
} else {
alert("Invalid Login");
}
}
$scope.register = function () {
window.location = "register.html";
}
});
The default behaviour for <button>s is to submit the form they are part of.
Change your code to this:
<button class="btn btn-default">LOGIN</button>
<button type="button" class="btn" ng-click="register();">SIGN UP</button>

Categories