pug/firebase: add users from input to firebase - javascript

I'm trying to add some users from a form to my firebase database. For that I've already linked up firebase config into my main.pug.
But nothing works, I've looked up everywhere and I'm pretty lost.
Need your help and sorry if the code is ugly.
There is my Addform.pug:
div
h2 Add Form
form#addForm
div
label(for='username') Username
input(type='text' name='username' placeholder='Username')#username
div
label(for='name') Name
input(type='text' name='name' placeholder='Name')#name
div
label(for='description') Description
textarea(type='text' name='description' placeholder='Description')#description
div
label(for='email') Email
input(type='email' name='email' placeholder='Email')#email
div
label(for='password') Password
input(type='password' name='password' placeholder='Password')#password
div
input(type='submit' value="ADD" onclick='writeUserData')
div
a(href='../src/editForm.html') Modify
And there my sxript:
// Variables
let username = document.querySelector('#username').value;
let name = document.querySelector('#name').value;
let email = document.querySelector('#email').value;
let password = document.querySelector('#password').value;
let description = document.querySelector('#description').value;
let users = document.querySelector('#users').value;
const submit = document.querySelector('#submit');
// Get a reference to the database service
const userRef = firebase.database().ref().child('Users');
// Add users
const writeUserData = () => {
userRef.push({
username,
name,
description,
email,
password
});
console.log(username, name, description, email, password);
}
// Display users
userRef.on('value', function (snap) {
console.log(snap.val());
users.innerText = JSON.stringify(snap.val(), null, 2);
});
// Delete user
function deleteUser() {
userRef.key('Users').remove();
}
It seems that I can't get the value, it's throwing me one error:
Uncaught TypeError: Cannot read property 'value' of null
Also I can neither see the hard coded data from firebase nor can delete my users.

The problem is your JavaScript selection code. document.querySelector("#xyz") is looking for the element with ID xyz. You have named inputs but would need to give your input elements corresponding IDs as well. An example would be
input#email(type='email', name='email', placeholder='Email')#email
Notice you also need to add a comma before the name attribute

Related

Having problems storing and displaying info in google firebase

I am trying to make a chatroom where the messages are stored in google firebase. I have not learned Javascript yet, but my schoolbook contains all the necessary Javascript code that I need for the task. The chatroom will have two inputs, one for username and one for a message, and a button to send the message. My problem is that whenever I try to send the message it won't store itself in the firebase and thus not be displayed. I apologize for the IDs and classes being in Norwegian, but I'm afraid that if I try to change it I will mess up something in the process.
<form id="skjema">
<input type="text" id="inpAvsender" required placeholder="Brukernavn">
<input type="text" id="inpMening" required placeholder="Melding">
<button type="submit" class="button">Send</button>
</form>
<article id="txtMeldinger"></article>
// google firebase snippet here //
<script>
let database = firebase.database();
let meldinger = database.ref("meldinger");
let skjema = document.
getElementById("skjema");
let inpAvsender = document.
getElementById("inpAvsender");
let inpMening = document.
getElementById("inpMening");
let txtMeldinger = document.
getElementById("txtMeldinger");
function visMelding(snapshot) {
let melding = snapshot.val();
let meldingTekst ='<p>
<b>${melding.avsender}:</b>
<i>${melding.tekst}</i>
</p>';
txtMeldinger.innerHTML = txtMeldinger.
innerHTML + meldingTekst;
}
function regNyMelding(evt) {
evt.preventDefault();
var nyMelding = {
avsender: inpAvsender.value,
tekst: inpMening.value
};
meldinger.push(nyMelding);
inpMening.value ="";
}
meldinger.on("child_added", visMelding);
skjema.onsubmit = regNyMelding;
</script>

Unable to retrieve data for displaying in the browser

I have a web app where I can login using Firebase. I know the details are stored in the Firebase database. I want the username value to be displayed on the browser in a certain field. Here are the screenshots.
This is the firebase data. In this picture, see the username karthik babu.
I want that username to be displayed on the area in the picture below:
So, instead of the username, I need the actual username value to be displayed.
Here is the code I tried:
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/plus.login');
firebase.auth().signInWithPopup(provider).then(function(user) {
var token = user.credential.accessToken;
var user = user.user;
var usersRef = firebase.database().ref("WoofyDesktop/UserList");
if (user) {
usersRef.child(user.uid).set({
useremail: user.email,
useruid: user.uid,
username: user.displayName
});
firebase retrieve code i tried:
var rootRef = firebase.database().ref().child("UserList");
rootRef.on("child_added", snap => {
var username = snap.child("username").val();
$("username").append("<div><a><label>" + username + "</label></a></div>");
console.log(username);
});
html code for username..
<div>
<a href="#" class="user">
<label for="username" id="username" >username</label>
</a></div>
Any suggestions on how or what I should change for displaying the required data?
Edit: Tried the updated query as in the answer by aks79 and this is what I am getting. Any insights?
You cannot embed another label inside a label tag
Limitations of label tag...
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label
use a different tag like div instead
try using it like
HTML Code
<div class="user" id="username"></div>
and the jquery as
$("#username").append("<a href='javascript:void(0)'><label>" + username + "</label></a>");

Display Firebase data previously/currently submitted

So I'm simply trying to make a page where I have an input for a user's name and age, then they submit that, and it sends that to the Firebase database, and that is working perfectly. The other thing I'm trying to do is display the data submitted in a "view" section. So just display the user's name and age below. I'm struggling to understand/get why my code is not working -- I have an h3 in place that should be replaced by the data that is stored in my database.
Here is my code for the retrieval section
'Age' is what one category of children is called (the other is 'Name')
<h2> View</h2>
<h3 id="showData"> Hello</h3>
<script>
showData = document.getElementByID('showData');
var firebaseDataRef = firebase.database().ref().child('Age');
firebaseDataRef.on('value', function(snapshot){
showData.innerText = snapshot.value;
});
the rest of my code:
<input type=text" id="userName">
<input type="number" id="userAge">
<button id="btUpdateMessage" margin-bottom="20px" onclick="addFB()"> Update</button>
<script>
var lblCurrentMessage = document.getElementById('lblCurrentMessage'),
userName = document.getElementById('userName'),
btUpdateMessage = document.getElementById('btUpdateMessage'),
userAge = document.getElementById('userAge'),
rootRef = new Firebase('https://addview-c21e6.firebaseio.com'),
currentMessageRef = rootRef.child('Name'),
currentNameRef = rootRef.child('Age');
function addFB()
{
currentMessageRef.push(userName.value);
currentNameRef.push(userAge.value);
userName.value = '';
userAge.value = '';
}
.value is not a property of DataSnapshot. You need to call the .val() method on it.
firebaseDataRef.on('value', function(snapshot){
showData.innerText = snapshot.val();
});
docs: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#val

Retrieving AND Displaying saved data from local storage inanother web page

I am doing a school project on creating a web site. I have managed to save user data into local storage upon signing up for an account. I want to retrieve and display the saved user data from local storage into an edit profile page, such that when I load the edit profile page, there would be some data already shown in the page.
For example in social media accounts whenever we want to edit our profile, our current information would be shown, and we just edit our info from that page. How do I achieve this?
Here are my codes:
<script>
var currentUser=null;
document.addEventListener("DOMContentLoaded",loadUserData);
function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);
console.log(currentUser.username);
console.log(currentUser.name);
console.log(currentUser.password);
console.log(currentUser.email);
}
}
</script>
I know the console.log only shows the data in console, but I need the data to be shown in the text box instead when users go to the edit profile page.
Is the following script correct to display a username in the username text box?It didn't work for me though.
<p>
<label for="newusername">Change Username:</label>
<input type="text" name="username" onload="valueAsPlaceHolder();"
id="username" required="required"/>
<!--<script>
function valueAsPlaceHolder() {
var changeUsernameInput = document.getElementById("username");
localStorage["username"] = changeUsernameInput.value;
var changeUsernameSetting = localStorage["username"];
if (changeUsernameSetting == null) {
changeUsernameInput.value = "";
}
else {
changeUsernameInput.value = changeUsernameSetting;
}
}
</script-->
</p>
You should have to modify the loadUserData function like below. I have set example for username you can follow for all fields like name, email and password.
function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);
document.getElementById('username').value = currentUser.username;
}
}

Using form element as variable in Firebase .child()

I would like to use the value of an input from a form element to add a child reference to my firebase data. But, the firebase .child() requires a string, and I've tried to insert a variable (whose value is a string) but it won't work. How do I by pass this?
For example here is a very simple code of an input and submit button. On submission, I want to take the username and add a child reference to my database (under /users ref) in this structure:
{username:{userid: "someID"}}
<html>
<body>
<form>
<input id="testusername" type="text">
<button type="submit" id="testsubmit" value="submit"></button>
</form>
<p>test file for .child()/p>
<script type="text/javascript">
$('#testsubmit').on('click',function(){
var elusername = document.getElementById('testusername');
var username = elusername.value;
alert('username is' + username)
var url = "https://thriftit.firebaseio.com/users";
var firebaseRef = new Firebase(url);
firebaseRef.child(username).push({
userid: "someID"});
});
</script>
</body>
</html>
There's a couple of things.
You're submitting the form before the javascript can run, you need to prevent the page from submitting the page on the click, so remove the type="submit"
I wouldn't do a child on the username, reason being if another user with the same username adds some data, then it would be added under the same username so you'll get two lots of data under the same username.
You want to so something similar to this:
$('#testsubmit').on('click',function(){
var elusername = document.getElementById('testusername'),
username = elusername.value,
url = "https://thriftit.firebaseio.com/users",
firebaseRef = new Firebase(url);
userRef = firebaseRef.push({
username: username,
userid: "someID"
});
console.log(userRef.name()); // this is the uid for the newly generated user
});

Categories

Resources