I was able to save the displayName to the user in Firebase, but I am not sure how to display that name on the page in JS.
Currently, I am using this:
document.getElementById('txtName').innerHTML = firebase.auth().currentUser.displayName;
Check if your element is correctly identified and display it to the console.
console.log(document.getElementById('txtName'));
The Firebase syntax is ok, just check the user against null, like:
var user = firebase.auth().currentUser;
var name, output;
output = document.getElementById("txtName");
if (user != null) {
name = user.displayName;
output.innerHTML= name;
}
Related
I have been trying to make a simple Register/Login system in JS. I tried to get the username/password values through user inputs and turn them into variables using a register() function. After that, however, these variables no longer hold any value, and I need them to compare with the new login username/password to check if they match in order to login.
Here's what I tried.
The function below attributes the user's input to the respective variables successfully. The ID's are from a text input in a HTML file.
function register () {
var user1 = window.document.getElementById('username')
var pass1 = window.document.getElementById('password')
alert('User registered, user your credentials to login')
}
When I click the 'register' button in the html page, the function is called (onclick="register()"), and I am redirected to the login page.
Here's the code for the login session:
function login () {
let userL = window.document.getElementById('usernameL')
let passL = window.document.getElementById('passwordL')
if (userL === user1 && passL === pass1) {
alert(`${userL} successfully logged`)
}
else {
alert('Invalid credentials')
}
It doesn't work because in the code above, user1 and pass1 are "not defined", according to the console. How do I keep the values of these variables stored after getting them in the first function(register) in order to use it when the second function(login) is used?
You can use Session storage to store temporary data
sessionStorage.setItem('username',username);
sessionStorage.setItem('password',password);
To retreive the data in login page
var user1 = sessionStorage.getItem('username',username);
var pass1 = sessionStorage.getItem('password',password);
then clear
sessionStorage.clear();
Please refer the below code,
<script>
const allUsers = [];
function register() {
// assuming user1 && pass1 are input elements with ids username, password
var user1 = document.getElementById("username").value;
var pass1 = document.getElementById("password").value;
// TODO: always validate the data that is taken as input from the user
// create an object containing user details
const newUser = {
username: user1,
password: pass1,
};
// push the registered user in allUsers array
allUsers.push(newUser);
alert("User registered, user your credentials to login");
}
function login() {
// assuming user1 && pass1 are input elements with ids usernameL, passwordL
let userL = document.getElementById("usernameL").value;
let passL = document.getElementById("passwordL").value;
// TODO: always validate the data that is taken as input from the user
// loop through allUsers array to check whether we already have a user registered with the details given in login form
for(let user of allUsers) {
if(user.username === userL && user.password === passL) {
alert(`${userL} successfully logged`);
return; // exit the function here
}
}
// if user detail not found in allUsers array this alert will be executed
alert("Invalid credentials");
}
</script>
Store all users in array after successful registration
While login, loop through the registered users array to check whether the user has already registered or not and decide how to handle the logic.
As PM 77-1 mentioned in the comment, please be aware that getElementById(ID) returns us the element itself (the tag itself), if we want to access it text content we can use either getElementById(ID).textContent or getElementById(ID).innerText
I've been trying for a project I'm working on to develop a function for a Food chatbot. What I'm currently working on is to perform a method for a user to make a purchase of an order that is stored in firebase realtime database.
The method is set as the method for an actionMap and the actionMap is linked to an intent for knowing when to call the method and for retrieving the parameters.
My current method uses a simple check for a user's existence and status within the database before identifying the existence of the order they're trying to make a purchase for by its id by going through the user's reference path and doing a .forEach to check every order found and look at its parent folder name to check if it matches the user's order id. My code is as follows:
const MakePurchaseACTION = 'Make Purchase';
function makePurchase(app){
let email = parameter.email;
let orderId = parameter.orderId;
var currDate = currDateGenerator();
var name = email.split(".com");
//Check if User exists first in database
var userRef = database.ref().child('user/' + name);
return userRef.once('value').then(function(snapshot) {
if (snapshot.exists()) {
let statusRetrieved = snapshot.child('Status').val();
//Check if user's status in database is signed in.
if (statusRetrieved == "Signed In") {
var orderRef = database.ref().child('order/' + name);
//Check the order table for the user.
return orderRef.once('value').then(function(orderSnapshot){
let orderVal = orderSnapshot.val();
console.log(orderVal);
//Check through every child for the matching id.
orderSnapshot.forEach(function(childSnapshot) {
let orderIdFound = childSnapshot.key;
//let cost = childSnapshot.child('Cost').val();
console.log(orderIdFound);
if(orderId == orderIdFound) {
let eateryName = childSnapshot.child('Eatery').val();
let eateryLocation = childSnapshot.child('EateryLocation').val();
let deliveryAddress = childSnapshot.child('DeliveryAddress').val();
let orderItem = childSnapshot.child('OrderItem').val();
let quantity = childSnapshot.child('Quantity').val();
let cost = childSnapshot.child('Cost').val();
var purchaseRef = database.ref().child('purchase/' + name + "/" + currDate + "/" + orderId);
purchaseRef.set({
"Eatery" : eateryName,
"EateryLocation" : eateryLocation,
"DeliveryAddress": deliveryAddress,
"OrderItem" : orderItem,
"Quantity": quantity,
"Cost": cost,
"DateCreated": currDate
});
app.add("You have successfully purchased Order " + orderId);
} else {
app.add("There is no order with that id.");
}
});
});
} else {
app.add("You need to be signed in before you can order!");
}
}
else {
app.add("Sorry pal you don't exist in the database.");
}
});
}
actionMap.set(MakePurchaseACTION, makePurchase);
After checking through some firebase logs
Firebase Logs screenshot here
Firebase Realtime Database Order Table Sample
I found that the method actually completes Purchase table sample but my dialogflow returns with the stated error of:
Error: No responses defined for platform: undefined and displays "Not Available" back to the user. My question is how do I go about resolving this error?
I'm trying to detect new visitor on my page, ask for his name using prompt and store it on local storage.
If he is a return user, show his name on the page using 'querySelector'.
I started from checking if it's a new user or not, but I got stuck.
var localStorage = window.localStorage;
if(localStorage.getItem("reutrn_user")) {
//
} else {
var name = prompt("Please enter your name");
localStorage.setItem('username', name);
}
Any idea how to get the username and show it in case he is a return user?
Thanks
Your getItem and setItem have different keys.
In your example, one key is reutrn_user and the other username.
var localStorage = window.localStorage;
if(localStorage.getItem("username")) {
console.log(localStorage.getItem("username"))
} else {
var name = prompt("Please enter your name");
localStorage.setItem('username', name);
}
Using Firebase, I am trying to display a user's profile information based on their user id. I can currently save data to the database under the users ID.
I am able to display the general information from hobbies, but when altering the variables to display the user's data the id is then null or uid undefined and i can't figure out why? The user is signed in, and can upload data using their id.
//Display Profile Information
(function(){
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
const preObject = document.getElementById('object');
const list = document.getElementById('list');
//Displays Hobbies correctly, When changing 'object' & 'hobbies'
//to 'Users' & uid nothing is shown.
const dbRefObject = firebase.database().ref().child('object');
const dbRefList = dbRefObject.child('hobbies');
dbRefObject.on('value', snap=> {
preObject.innerText = JSON.stringify(snap.val(), null, 3);
});
dbRefList.on('child_added', snap => console.log(snap.val()));
};
Alterations:
const dbRefObject = firebase.database().ref().child('Users');
const dbRefList = dbRefObject.child(uid);
I am extremely grateful for any help or advice!
It looks like you are getting a value for dbRefObject which is pointed to the entire Users object and not a specific user's UID.
Try changing this:
dbRefObject.on('value', snap=> {
preObject.innerText = JSON.stringify(snap.val(), null, 3);
});
to this (dbRefObject changes to dbRefList):
dbRefList.on('value', snap=> {
preObject.innerText = JSON.stringify(snap.val(), null, 3);
});
the player can simply enter pseudo name (in login page) to be able to enter the app and play; meteor attribute id for each document but not for user;
When I set Meteor.userId(), it returns "null";
How is it possible to make Meteor returns also userId ??
edit:
the purpose of getting userId is to be able to remove user document form collection when the time is over , here is my remove code :
in client
if (nombrePo == 11 ) {
var nombreL = NLevels.findOne({userID:ad}).level;
var nombreLo = nombreL + 1;
Meteor.call('update_level', nombreLo);
var nom1 = function(){if(Meteor.user()) { return Meteor.user().services.facebook.name; }else{ return localStorage.getItem("frontlog");}}
var nom = nom1();
var ad = Meteor.userId();
var nombreP = NPortes.findOne({userID: ad}).portes;
var nombrePo = nombreP + 1;
Meteor.call('remove_item',nombreP,nom,ad);
Router.go('overR');
delete Session.keys['times'];
};
in collection
Meteor.methods({
'remove_item': function(nombrePo,nom,ad){
NPortes.remove({
portes: nombrePo,
nom: nom,
userID: ad
});
}
});
as Meteor.userId() is null, I can't remove user's document
Thank's for help
You can register the user when entering their pseudo name.
Accounts.createUser(options, [callback]);
Then the user will be logged in and you can call Meteor.userId() to the get the current user id which will not be null.
http://docs.meteor.com/#/full/accounts_createuser