Firebase Data Not Saving to Database - javascript

I'm having a problem attempting to add data to Firebase. Disregard the vars I don't use as I am trying different things and have commented out stuff I am not using at the moment.
But essentially, what I want to do is save this data to Firebase as follows:
A user enters his name and age in input boxes and then hits submit.
Once he/she hits submit, the function addFB() runs and ideally would create a child called users, and then under that, create a new child with the newly typed in userName (the User's name from the input box), and store his name and age in that child.
However, nothing is going to Firebase from this. Please help. Thanks in advance!
<h2>Add</h2>
<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://********.firebaseio.com');
var usersRef = rootRef.child('users');
function addFB() {
usersRef.child(userName).set({
Name: userName,
Age: userAge
});
userName.value = '';
userAge.value = '';
}

*rootRef = new Firebase('https://********.firebaseio.com');*
The above code is not correct. This is the old method.
Just check the below code. This will help you.
function addFB() {
var userName = document.getElementById('userName'),
userAge = document.getElementById('userAge');
firebase.database().ref('users/' + userName).set({
Name: userName,
Age: userAge
});
}

What about this?
var rootRef = Firebase('https://********.firebaseio.com');
var contactsRef = rootRef .child('users');
function addFB() {
contactsRef.child(userName)
.push({
userName: document.getElementById('userName').value,
userAge: document.getElementById('userAge').value
});
Name.value = '';
Age.value = '';
}

Related

JavaScript - Form validation, want username/password validation but it submits with no issues

I'm sure I'm missing something obvious here but I've had a really good look over this, combing for typos and such but I can't see what the problem is. I want this to be a simple form that requires a username/password combination to validate. The usernames/passwords having to match hasn't been implemented yet because my initial testing can't get over this first hurdle of the form always validating!
I've definitely made a solid go at it and I feel bad I'm getting stuck here, even looking over tons of references and comparing them to my own. I'm not even sure if the event listener itself is the problem or if the problem comes from poor coding in the function. Opening console in browser shows me no errors either. Could anybody point out where my issue is? Thanks.
"use strict";
let loginform = document.forms.login;
loginform.addEventListener("submit", checkLogin);
let users = [];
let pwords = [];
users = ["Administrator", "Manager", "Cleric", "Scribe"];
pwords = ["Password01", "Password", "Admin", "P#ssword"];
//*** NOTE: the password for each username is specific. Use the the alignment of the data in the table above (i.e. the password for the Administrator account is Password01, etc.). ***
function checkLogin() {
var usernameInput = loginform.getElementById("Username").value;
var pwInput = loginform.getElementById("Password").value;
//.includes is what we need for the array checking if statements
//For Loop 1
for (usernameInput in users) {
if (!users.includes(usernameInput)) {
window.event.preventDefault();
alert("Your username is incorrect. Please try again.")
loginform.user.focus();
return false;
} else {
//For Loop 2
for (pwInput in pwords) {
if (!pwords.includes(pwInput)) {
window.event.preventDefault();
alert("Your password is incorrect. Please try again.")
loginform.pword.focus();
return false;
}
}
}
}
}
<h1 id="main">Login to Umbrella Corporation</h1>
<div id="container">
<form name="login" action="success.html" method="POST">
<input type="text" name="user" id="Username">
<br>
<br>
<input type="password" name="pword" id="Password">
<br>
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</div>
The form element does not have a getElementById.
Change to one of these
var usernameInput = loginform.user.value;
var pwInput = loginform.pword.value;
var usernameInput = loginform.querySelector("#Username").value;
var pwInput = loginform.querySelector("#Password").value;
var usernameInput = document.getElementById("Username").value;
var pwInput = document.getElementById("Password").value;
You do NOT need to loop and then use includes
if (!users.includes(usernameInput))
is enough
Here is an optimised test
function checkLogin(e) { // event is available here
const usernameInput = loginform.user.value;
const pwInput = loginform.pword.value;
if (!users.includes(usernameInput)) {
e.preventDefault();
alert("Your username is incorrect. Please try again.")
loginform.user.focus();
return false;
} / no need for else after a return
if (!pwords.includes(pwInput)) {
e.preventDefault();
alert("Your password is incorrect. Please try again.")
loginform.pword.focus();
}
}
I think the problem here is that you're trying to loop through your data using the input provided:
var usernameInput = loginform.getElementById("Username").value;
for (usernameInput in users) {...}
This won't work. What you can do is find if the username that the user has provided is present in the array.
var usernameInput = loginform.getElementById("Username").value;
const userIndex = users.indexOf(usernameInput);
If a user is found, it will return a valid index, else it'll return a -1. You can use this to throw an error to the user.
You can do the same with the password:
var pwInput = loginform.getElementById("Password").value;
const pwIndex = pwords.indexOf(pwInput);
At the final check, you can compare the two indices. If they are equal, they are the right combo, else it's an incorrect username/password combo.
if(pwIndex === userIndex && pwIndex !== -1){...} // Success
else {...} // Failure
Finally, this is how your JavaScript should look like:
function checkLogin() {
var usernameInput = loginform.getElementById("Username").value;
var pwInput = loginform.getElementById("Password").value;
//.includes is what we need for the array checking if statements
const userIndex = users.indexOf(usernameInput);
const pwIndex = pwords.indexOf(pwInput);
if(userIndex === -1 || pwIndex === -1) {
alert("Your username/password is incorrect"); // Always better to provide a generic error. You don't want malicious users to know which part they're getting wrong.
}
}

How to edit and update data in local storage?

I've been researching for hours and asked a number of times in stack overflow, but the answers did not help or I don't understand at all (user made use of jquery and php as part of solution which I do not know how to use)
Here are my codes (currentuser-will only show when user is logged in)
var currentUser=userList;
document.addEventListener("DOMContentLoaded",loadUserData);
function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);
document.getElementById('username').value = currentUser.username;
document.getElementById('name').value = currentUser.name;
document.getElementById('password').value = currentUser.password;
document.getElementById('email').value = currentUser.email;
console.log(currentUser.username);
console.log(currentUser.name);
console.log(currentUser.password);
console.log(currentUser.email);
}
}
My codes to add users as objects into an array when they sign up for an account:
var userList;
document.addEventListener("DOMContentLoaded", loadUserList);
function loadUserList(){
if(localStorage.getItem("userList")===null) {
userList = [] ;
} else {
userList = JSON.parse(localStorage.getItem('userList'));
}
}
function saveUserToStorage(){
var u=document.getElementById("username").value;
var n=document.getElementById("name").value;
var p=document.getElementById("password").value;
var e=document.getElementById("email").value;
var user={"username":u,"name":n,"password":p,"email":e};
localStorage["user"]=JSON.stringify(user);
userList.push(user);
localStorage.setItem('userList',JSON.stringify(userList));
}
When I log in, it would direct me to the edit profile page and display data in the form which the user had entered when signing up.
What I NEED right now is just to change the local storage data by filling in the form. Just like editing it through the Inspect Element, just that it's being edited through the edit profile form. How do i achieve this?
Please help me. Would appreciate solutions without jquery/php
Sample of local storage:
Before editing
{"username":"alice66","name":"alice tan","password":"123","email":"abc#mail.com"}
After editing (through edit profile page)
{"username":"ben66","name":"ben ong","password":"qwerty","email":"xyz#mail.com"}
What would be the correct function to do so?
I tried the following function but it did not work:
var updatedUser=currentUser;
document.addEventListener("DOMContentLoaded",saveChanges);
function saveChanges() {
updatedUser = localStorage.getItem("updatedUser");
updatedUser = JSON.parse(updatedUser);
var u = document.getElementById("username").value = updatedUser.username;
var n = document.getElementById("name").value = updatedUser.name;
var p1 = document.getElementById("password1").value = updatedUSer.password1;
var p2 = document.getElementById("password2").value = updatedUser.password2;
var e = document.getElementById("email").value = updatedUser.email;
updatedUser={"username":u,"name":n,"password1":p1,"password2":p2,"email":e};
updatedUser.push(updatedUser);
localStorage.setItem('updatedUser',JSON.stringify(updatedUser));
}
It is rather simple
https://jsfiddle.net/ft3ur0cw/5/
<input placeholder="name" id="name"><br/>
<input placeholder="nausernameme" id="username"><br/>
<input placeholder="password" id="password"><br/>
<input placeholder="email" id="email"><br/><br/>
<button id="save" >save</button>
<br/><br/>
<input placeholder="name_saved" id="name_saved"><br/>
<input placeholder="nausernameme_saved" id="username_saved"><br/>
<input placeholder="password_saved" id="password_saved"><br/>
<input placeholder="email_saved" id="email_saved"><br/><br/>
function load_user(){
var userdata = localStorage.getItem("userdata");
if(typeof userdata === undefined || userdata === null){
userdata = JSON.stringify({username:"",name:"",password:"",email:""});
localStorage.setItem("userdata",userdata);
}
return JSON.parse(userdata);
}
function save_user(username , name, password, email){
userdata = JSON.stringify({username:username,name:name,password:password,email:email});
localStorage.setItem("userdata",userdata);
return userdata;
}
document.getElementById('save').addEventListener("click",function(){
save_user(
document.getElementById('username').value,
document.getElementById('name').value,
document.getElementById('password').value,
document.getElementById('email').value
);
userdata = load_user();
document.getElementById('username_saved').value = userdata.username;
document.getElementById('name_saved').value = userdata.name;
document.getElementById('password_saved').value = userdata.password;
document.getElementById('email_saved').value = userdata.email;
});
userdata = load_user();
document.getElementById('username_saved').value = userdata.username;
document.getElementById('name_saved').value = userdata.name;
document.getElementById('password_saved').value = userdata.password;
document.getElementById('email_saved').value = userdata.email;
this is pretty much how it goes.
EDIT:
better example demonstrating the use of the functions

localstorage and JSON

I need some help with figuring out how local storage and JSON works.
I have the following html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="Script.js"></script>
</head>
<body>
<form name="test" method="post" action="javascript:storage()">
<input name='surname' id="surname" value='surname'>
<input name='lastname' id="lastname" value='lastname'>
<input type="submit" value="test">
</form>
<div id="tabletest"></div>
</body>
</html>
the following javascript:
function storage(){
var surname = document.getElementById('surname').value;
var lastname = document.getElementById('lastname').value;
var person = {
"surname" : surname,
"lastname" : lastname,
"dateofbirth" : "01-01-1990"
};
person = JSON.stringify(person);
localStorage.setItem('person', person);
var person2 = localStorage.getItem('person');
var persons = JSON.parse(person);
var tabletest = document.getElementById('tabletest');
var person3 = JSON.parse(person2);
tabletest.innerHTML += JSON.stringify(person3);
}
My problems/troubles:
The output I get in tabletest is this:
{ "surname":"surname", "lastname":"lastname", "geboortedatum":"01-01-1990" }
How do I get only the surname and the lastname in the 'tabletest' div?
How do I add a new value with the inputs from the textfields when the submitbutton is clicked (because push doesn't work)?
To get lastname(or I should say any value inside JSON) use
tabletest.innerHTML +="Lastname:"+person3.lastname+" Sirname:"+person3.sirname;
And to add to the JSON use:
person.newName = newName
//or
person["newName"] = newName;
Localstorage works on key-value pairs. Since you are using the same key, 'person', you are simply overwriting previous value. You could use an array of persons which you store using 'person' key but you are responsible for parsing/stringifying the array each time.
var personsStore = [];
function storage() {
var s = localStorage.getItem("person");
if (s) {
personsStore = JSON.parse(s);
}
var person = {...} //after you get properties from dom input
personsStore.push(person);
var stringForm = JSON.stringify(personsStore");
localStorage.setItem("person", stringForm);
var tabletest = document.getElementById('tabletest');
tabletest.innerHtml += stringForm;
}
If you want particular attributes the easiest way to do that is to use a tool like underscore (underscore.org). Appending to 'tabletest' becomes
tabletest.innerHtml += JSON.stringify(_.map(personStore, fucntion(p) {
return _.pick(p, "firstname", ....);
});
Here is a fiddle
Right now, your logic shows you grabbing the value of first and last name, which is, currently: surname and lastname, respectively:
<input name='surname' id="surname" value='surname'>
<input name='lastname' id="lastname" value='lastname'>
You need to run this function on the button click event and get the value and simply use the storage setItem(key,value) function. Here is the documentation . You only need to stringify, then parse on the storage data. After that, it is an object that you can get the properties from.
person = JSON.stringify(person);
localStorage.setItem('person', person);
var person2 = localStorage.getItem('person');
var persons = JSON.parse(person2);
var tabletest = document.getElementById('tabletest');
tabletest.innerHTML += persons.surname + ' ' + persons.lastname;
You were very close on the logic, but you needed something like this:
document.getElementById('btnTest').onclick = storage;
I also modified the 'submit' button to a standard 'button' element so that the form doesn't post:
<button id='btnTest' value="test">Test</button>
You could then do Ajax. Otherwise, you would need to do a pre-submit function

setting form input to a value in firebase

Another Questions here,
I am trying to copy an input (or a value) from an input on my form to fire values,here is my code :
<script>
var dataBase = new Firebase ('https://yjyc-signup.firebaseio.com/Entries');
var fName = document.getElementById('name');
var eMail = document.getElementById('email');
var submitBtn = document.getElementById('submit');
//var phoneNumber = document.getElementById('phonenumber');
var nameRef = dataBase.child('Name');
var emailRef = dataBase.child('Email');
//var phonenumberRef = dataBase.child('phone number');
submitBtn.addEventListener('click', function(){
dataBase.push({ 'name': 'hello', 'Email': 'Email', 'Phone number': 'phonenumber' });
//nameRef.set(fName.value);
//emailRef.set(eMail.value);
//phonenumberRef.set(phoneNumber.value);
swal("Thanks Alot!", "Thank you for signing up, a representative will be in touch with you shortly", "success")
});
</script>
as you can see the 'name': is harcoded to hello , but I am looking to link it to the value of the name input at the form.
any suggestions?
Thank you so much for you help.
To set the dynamic value instead of hardcoded one you just need to use variables. Based on your code something like this should do the trick:
dataBase.push({ 'name': document.getElementById('name').value, 'Email': document.getElementById('email').value, 'Phone number': document.getElementById('phonenumber').value });

dynamically check form field values javascript

Is it possible to check the form field values dynamically with javascript only.
For example if I have form field for username and when the user enters their chosen username it checks whether this username is available and pops up an alert box or shows a message on the screen based on the result.
all of this is done without clicking any button. and the data is stored in an array.
Thanks in advance. Im trying to achieve this only by using javascript.
var username = document.getElementById('username');
var goBtn = document.getElementById('check');
var output = document.getElementById('output');
var usernames = ['bob', 'sally', 'alice', 'roy', 'kate', 'phil'];
function showResult() {
output.innerHTML = usernames.join(', ');
}
function checkUsername() {
if (usernames.indexOf(username.value) < 0) {
usernames.push(username.value);
username.value = '';
} else {
alert('That username is already taken. Try again.');
}
showResult();
}
goBtn.onclick = checkUsername;
showResult();
<label for="username">Name:</label>
<input id="username" name="username" placeholder="username">
<button id="check">Go</button>
<div id="output"></div>
may be this is what you want
// usernameArray contains all the usernames that can't be used
var usernameArray = ['username1','username2','username3'];
// i'm using .kyup() method to get a dynamic result so whenever the user type a letter or
// something else (just one caracter) we check that value against our usernameArray list
$('#username').keyup(function(){
var value = $(this).val();
if(usernameArray.indexOf(value) >= 0){
alert('sorry, try another username ');
}else{
alert('good, you can use this username it is available');
}
});

Categories