I am trying to display an input area in a Jade file with pre-populated data gathered from the session info being stored in mongodb session store. The web app is built on Express for node.js. My Jade file looks like this with the input area (pre-populated with session data):
input(name='username', value='#{username}')
So the input area is displaying the correct username stored in the session. Then, I want the user to be able to edit that field and submit a new username if desired. My mongodb update() looks like this:
uname = request.body.username;
targetcol.update({username: req.session.username, password: req.session.password}, {username: uname});
Once submitted however, the document in the mongodb collection for the related profile is not being updated, it's keeping the same value that's been pre-populated. I'm wondering if this is because I'm assigning it as a value= in the Jade file? Any advice on what is wrong and how to fix it?
Assuming you are using a form, access the value attribute of the input with name username from your route handler function using req.body.username:
app.use(express.bodyParser());
app.post('/form', function(req, res){
var newUsername = req.body.username;
targetcol.update({ username: req.session.uname, password: req.session.password}
, {username: newUsername});
res.redirect('/');
});
The answer was on the mongodb update() side of things. I left a big part out of my question apparently... The selection criteria was actually this:
input(name='username', value='#{username}', disabled)
I didn't realize disabled fields would pass in undefined values, I just thought it made them un-editable. So the update() wasn't working because it couldn't find any matching documents in the collection because username was undefined. You know what they say about assumptions!
I'll credit you #Plato with the answer though, the hint to investigate the values is what lead me to figure this out.
Related
I'd like to build a website which has the following features:
There should be a few fields which store numerical values.
These fields should be editable by anyone who visits the site
A second order feature which would be nice, but isn't necessary
It would be nice if when multiple people are visiting the site and one visitor updates a value, the webpage reloads for all visitors once the value is saved, updating the value seen for all users
How would I go about implementing the above?
I'm not sure what terms I should even be googling to approach this question, so any advice is appreciated.
To your first question:
const editMe = document.getElementById('edit-me');
editMe.addEventListener('input', () => {
const editedToInt = Number(editMe.innerHTML);
if (!Number.isInteger(editedToInt)) {
// Value is invalid
editMe.style.border = "2px solid red";
}
else {
// Value is valid. Do something with it...
editMe.style.border = "inherit";
}
})
<div id="edit-me" contenteditable>100</div>
The user can edit the content and only numbers are allowed.
To your second question:
You could save the value which the user has typed in your database. Also you need to use Ajax to check the value in your database every 5 seconds. If the value in your database is different than the value in the DOM, you will replace it.
I am using a form builder using which my admin side can create forms and store it as JSON. They are rendered dynamically when the client accesses these forms. When the client submits the form at the back end I need to get the value of all the fields.
Currently I am trying to do this as follows:(Node Server)
router.post('/increase', function (req, res, next) {
req.session.counter++;
var ans = req.body;
console.log(ans+" this got printed");
res.redirect('docfill');
});
I cannot specify a name after req.body as i dont know the field name due to the dynamic nature of the forms.
The console prints [Object object]. The currently rendered form has a date field I need. And if I put it through JSON.stringify() it prints {}. Is my fetched data coming out to be blank? Could it be a problem with using the data field.
EDIT
its not because the filed is a date type, dosnt work with text either
There could be 2 reasons for this:
You have not installed/required the bodyParser module.
In your form tag you're using the enctype attribute as enctype="multipart/form-data". Reason for this being you're not using any module for handling the multipart/form-data type which is unreadable by the browser. Use enctype="application/json" instead.
I am stuck on this and the other posts I have read on here are not useful. So I've reached a point where i need to ask for help after many hours on not resolving what I feel should be a simple task. I program in Swift usually and really know little about html or javasript.
I am building a simple webpage to log-in to Firebase and a second linked page to upload data to a database. Both work fine. The problem is getting the uploaded data to link to the uid of the current user.
So I am logged into an existing user with it's own uid. How do I then upload the data to the current user did in the database? Should be simple but I am just not getting it :-(
Code for uploading data is as follows (note I have tried using both set and push):
// Generate a reference to a new location and add some data using push()
var postsRef = ref.child("users");
var newPostRef = postsRef.push({
// var newPostRef = postsRef.set({
name: _name,
property: _property,
email: _email,
phone: _phone,
Any help, or better still a working simple example would be useful. I have read the docs on Firebase, so please don't direct me there :-)
Many thanks in anticipation
It is a best practice to create a new database node using the UID generated by the account creation as the path after /users.
Right now, when you push data into /users, Firebase creates a uid for that particular array item that does not correspond to the UID of the user.
If you use set, you need to specify the path you will set which should include the long UI: /users/longGUIDhere
You can get the user id with something like this (from Firebase docs):
var user = firebase.auth().currentUser;
var name, email, photoUrl, uid;
if (user != null) {
name = user.displayName;
email = user.email;
photoUrl = user.photoURL;
uid = user.uid; // The user's ID, unique to the Firebase project. Do NOT use
// this value to authenticate with your backend server, if
// you have one. Use User.getToken() instead.
}
And then you shouuld use uid to populate the path like below to save their info:
function writeUserData(userId, name, email, imageUrl) {
firebase.database().ref('users/' + userId).set({
username: name,
email: email,
profile_picture : imageUrl
});
}
I know you asked not to be referred to the Firebase docs, but it also looks like you are using an older version of the SDK, so that could be part the issue as well. I recommend taking a look at these two page, since that is where I pulled these verbatim examples:
https://firebase.google.com/docs/database/web/read-and-write
https://firebase.google.com/docs/auth/web/manage-users
var postsRef = ref.child("users/current user id or json key");
this will help you to update the details of current user.
I found this great node mysql boilerplate:
https://github.com/ocastillo/nodejs-mysql-boilerplate
it works terrific! However, now I need to hook it in to my existing user table, and my key field is named userID, not simply id, and changing the key fieldname in mysql breaks the example. So my question is, where in the project do I need to specify a different id field name? I see user.id in /util/auth.js passport.serializeUser and id in passport.deserializeUser functions, but it seems it must be specified elsewhere too. I'm hoping this is a simple question for users of passportjs!
Yes, you should only need to change the code in the serializeUser and deserializeUser functions. Those two functions you control, and state within them what you'd like to serialize into the session cookie (when the user logs in), and deserialize from the session cookie (when the user revisits the site after logging in). Think of them as ways to remember who this person is, once they return. The passport.use function is only used to define the authentication strategy, and within that, the manner in which you'll "log the user in".
So this should work (assuming I've followed what you've said above):
passport.serializeUser(function(user, done) {
done(null, user.userID);
});
passport.deserializeUser(function(user_id, done) {
new data.ApiUser({userID: user_id}).fetch().then(function(user) {
return done(null, user);
}, function(error) {
return done(error);
});
});
You might benefit from more examples, here's a gist I put together on passport configuration within Node (however this one uses Mongo): https://gist.github.com/dylants/8030433
So, I'm working with localstorage and need to create a login page. That will only login with those users that register in that same browser/mobile phone were the registe was done. The problem that I'm facing is that, I can only have on pair user/password because I dont know how to check it. I'll explain: if I have more that one user, it would login with any user/pass as long they where in the localStorge, and not necessarily with the corresponding ones. I need to check if the user is the "owner" of that password.
You will have to serialize an array to localStorage.
// to store some logins:
var logins=[];
logins[0]={username: someusername, password: somepassword };
logins[1]={username: someotherusername, password: someotherpassword };
localStorage['logins']=JSON.stringify(logins);
// to fetch all:
var storedLogins=JSON.parse(localStorage['logins']);