LocalStorage only storing last entered data - javascript

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

Related

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

javascript : sending custom parameters with window.open() but its not working

<html>
<head>
<script>
function open_win()
{
window.open("http://localhost:8080/login","mywindow")
}
</script>
</head>
<body>
<input type="button" value="Open Window" onclick="open_win()">
</body>
</html>
Hi ,
On click of a button , i am opening a new website (My web site )
I have two text fields ( One Text Field and another Password Field) , i am trying to send this values to the other opened window .
But its not working as I want.
I have tried the following ways
1. window.open("http://localhost:8080/login?cid='username'&pwd='password'","mywindow")
2. window.open("http://localhost:8080/login","mywindow")
mywindow.getElementById('cid').value='MyUsername'
mywindow.getElementById('pwd').value='mypassword'
Could anybody please help me if this is possible or not ??
Sorry for the incomplete details , its a Post request .
if you want to pass POST variables, you have to use a HTML Form:
<form action="http://localhost:8080/login" method="POST" target="_blank">
<input type="text" name="cid" />
<input type="password" name="pwd" />
<input type="submit" value="open" />
</form>
or:
if you want to pass GET variables in an URL, write them without single-quotes:
http://yourdomain.com/login?cid=username&pwd=password
here's how to create the string above with javascrpt variables:
myu = document.getElementById('cid').value;
myp = document.getElementById('pwd').value;
window.open("http://localhost:8080/login?cid="+ myu +"&pwd="+ myp ,"MyTargetWindowName");
in the document with that url, you have to read the GET parameters. if it's in php, use:
$_GET['username']
be aware: to transmit passwords that way is a big security leak!
Please find this example code, You could use hidden form with POST to send data to that your URL like below:
function open_win()
{
var ChatWindow_Height = 650;
var ChatWindow_Width = 570;
window.open("Live Chat", "chat", "height=" + ChatWindow_Height + ", width = " + ChatWindow_Width);
//Hidden Form
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "http://localhost:8080/login");
form.setAttribute("target", "chat");
//Hidden Field
var hiddenField1 = document.createElement("input");
var hiddenField2 = document.createElement("input");
//Login ID
hiddenField1.setAttribute("type", "hidden");
hiddenField1.setAttribute("id", "login");
hiddenField1.setAttribute("name", "login");
hiddenField1.setAttribute("value", "PreethiJain005");
//Password
hiddenField2.setAttribute("type", "hidden");
hiddenField2.setAttribute("id", "pass");
hiddenField2.setAttribute("name", "pass");
hiddenField2.setAttribute("value", "Pass#word$");
form.appendChild(hiddenField1);
form.appendChild(hiddenField2);
document.body.appendChild(form);
form.submit();
}
To concatenate strings, use the + operator.
To insert data into a URI, encode it for URIs.
Bad:
var url = "http://localhost:8080/login?cid='username'&pwd='password'"
Good:
var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;
The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.
… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).
You can use this but there remains a security issue
<script type="text/javascript">
function fnc1()
{
var a=window.location.href;
username="p";
password=1234;
window.open(a+'?username='+username+'&password='+password,"");
}
</script>
<input type="button" onclick="fnc1()" />
<input type="text" id="atext" />
You can try this instead
var myu = document.getElementById('myu').value;
var myp = document.getElementById('myp').value;
window.opener.location.href='myurl.php?myu='+ myu +'&myp='+ myp;
Note: Do not use this method to pass sensitive information like username, password.
I found this method very useful, I hope this will be helpful for many users too.
// --> screen 1:
var url = 'screen_2_url';
var id = 'some_ID';
window.open(url + '?id=' + id);
This will open the Screen 2 tab. There you can get the passed values like this:
// --> screen 2:
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const id = urlParams.get('id');
I agree that passing username and password as parameters is a bad idea, no matter how you do it.
However, if it's same site, you could use sessionStorage, like so:
sessionStorage.setItem('username', username)
sessionStorage.setItem('password', password)
window.open("http://localhost:8080/login","mywindow")
And then in the opened window:
var username = sessionStorage.getItem('username')
var password = sessionStorage.getItem('password')
// if you no longer need them:
sessionStorage.removeItem('username')
sessionStorage.removeItem('password')

Categories

Resources