Retrieving AND Displaying saved data from local storage inanother web page - javascript

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;
}
}

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>");

Firebase email verification workflow

I have a simple input box asking for users emails.
I want them to input something, for me to check it is a string, and then send a verification email to their email address entered.
Then once verified within users mail client and the link is clicked, I want the user to be added to my Firebase users.
At the moment, I am just testing without any email sending via SMTP, just adding data to Firebase. However, no emails I add are being added to my Firebase database.
Current code in the bottom of the body of the HTML, before the other script tags (should this be in the head?):
<script src="https://www.gstatic.com/firebasejs/3.6.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "myapikey",
authDomain: "mydomain.firebaseapp.com",
databaseURL: "https://mydomain.firebaseio.com",
storageBucket: "mydomain.appspot.com",
messagingSenderId: "mymessagesenderid"
};
firebase.initializeApp(config);
</script>
<script src="assets/js/saveEmail.js" type="text/javascript"></script>
Then I have an input box:
<div class="mtb">
<h2 class="signup-title">Sign up for updates on our project</h2>
<p id="signup-success" class="text-success"></p>
<p id="signup-error" class="text-danger"></p>
<form class="signup-form form-inline" id="signup-form" role="form" onsubmit="return signup(this)">
<div id="div">
<input type="email" name="email" class="subscribe-input" placeholder="Enter your e-mail address..." required>
<button class='btn btn-conf btn-yellow' id="signup-button" type="submit">Submit
</button>
</div>
</form>
</div>
And this is saveEmail.js:
var signupForm = document.getElementById('signup-form');
var signupSuccess = document.getElementById('signup-success');
var signupError = document.getElementById('signup-error');
var signupBtn = document.getElementById('signup-button');
var onSignupComplete = function (error) {
signupBtn.disabled = false;
if (error) {
signupError.innerHTML = 'Sorry. Could not signup.';
} else {
signupSuccess.innerHTML = 'Thanks for signing up!';
// hide the form
signupForm.style.display = 'none';
}
};
function signup(formObj) {
// Store emails to firebase
var myFirebaseRef = new Firebase("https://mydomain.firebaseio.com/signups");
myFirebaseRef.push({
email: formObj.email.value,
}, onSignupComplete);
signupBtn.disabled = true;
return false;
}
I know that the signup function is being called as I tried a simple JS alert, which does pop up when the submit button is clicked. However, I am seeing nothing change in my Firebase data dashboard under the /signups section. Also, the URL changes to:
http://localhost:5000/?email=theemailthatwasputintothebox
I modified my rules to:
{"rules":
{".read": true,
".write": true
}
}
So I assume this is not about rules as I have enabled everything for testing purposes.
How can I achieve what I want to achieve (without, and then with the email confirmation part)?
What is going wrong with the existing setup, without email confirmation via SendGrid etc?
I have a simple input box asking for users emails.
I want them to input something, for me to check it is a string, and
then send a verification email to their email address entered.
Then once verified within users mail client and the link is clicked, I want the user to be added to my Firebase users.
I do not think Firebase works that way. Unless the user is registered, you cannot send a verification email to an arbitrary email address. The sendEmailVerification method works on a currentUser.
According to the docs:
You can send an address verification email to a user with the sendEmailVerification method
Now, to your snippet, aren't you simply trying to take a user input and save it to the database? With the recent SDK, you can try this, as per docs
....
var database = firebase.database();
function signup(formObj) {
// Store emails to firebase
database.ref('signups')
.push({
email: formObj.email.value,
})
.then(function(res) {
console.log(res)
// call whatever callback you want here
})
.catch( .... )
}
FYI if you are using Firebase email verification think about testing it during your end-to-end or smoke tests.
Use a service like emaile2e.com to generate random email addresses during a test which you can send and receive from. That way you can verify users during a test programmatically.

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

LocalStorage only storing last entered data

I am using LocalStorage to store username and password on an app I'm building with PhoneGap for iOS. When I run the app on my iPad, and I enter the username and password, close the app, then open again to enter another username and password. When I connect my iPad with my Macbook and open Safari Web inspector to inspect my app running on the iPad, when I go to "Storage -> localStorage" within the inspector, only the last entered username and password is displayed, but the first set of username and password I entered is no where to be found. Anyone have any ideas as to why this happens?
js:
<script type="text/javascript">
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
document.getElementById("btnSave").addEventListener("click",saveData,false);
document.getElementById("btnGet").addEventListener("click",getData,false);
}
function saveData(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
window.localStorage.setItem("uname", username);
window.localStorage.setItem("pass", password);
alert("Your data is stored");
}
function getData(){
var output="Your username is " + window.localStorage.getItem("uname") + "and your password is " + window.localStorage.getItem("pass");
document.getElementById("result").innerHTML = output;
}
</script>
html:
User Name: <input type ="text" id="username" /><br />
Password: <input type="text" id="password" /><br />
<button id="btnSave"> Save Data </button>
<button id="btnGet"> Get Data </button>
<div id="result"></div>
I've tried looking everywhere around the web inspector but still couldn't find where my first set of stored data went. Is there something wrong with the code?
Please try this
var localObject = [];
var testObject = {userName : "firstUser", password : "password1"};
localObject.push(testObject);
localStorage.setItem("userDetails", JSON.stringify(localObject));
console.log(JSON.parse(localStorage.getItem("userDetails")));
//for second time
var testObject = {userName : "secondUser", password : "password2"};
localObject.push(testObject);
localStorage.setItem("userDetails", JSON.stringify(localObject));
console.log(JSON.parse(localStorage.getItem("userDetails")));
Every time you try to store the user details, fetch the local storage, push the user details as an object into the array.
LocalStorage just stores key value pairs. To store more than one value use a workaround:
str=localStorage.getItem("users");
if(str==""){
str="[]";
}
users=JSON.parse(str);
//users contains an array now
users.push("John");
//add a user
localStorage.setItem("users",JSON.stringify(users));
//create json and store it again
Try this
var localObject = [];
localObject = localStorage.getItem("userDetails");
var testObject = {userName : "firstUser", password : "password1"};
var testArray = localObject.push(testObject);
localStorage.setItem("userDetails", JSON.stringify(testArray));
//to fetch the data
localStorage.getItem("userDetails");
console.log (JSON.parse(localStorage.getItem("userDetails")));
//for second time
var localObject = localStorage.getItem("userDetails");
var testObject = {userName : "secondUser", password : "password2"};
testArray = localObject.push(testObject);
localStorage.setItem("userDetails", JSON.stringify(testArray));
console.log (JSON.parse(localStorage.getItem("userDetails")));

Categories

Resources