I want to save and get out the Usernames from the Local Storage. I can only save and get out one Username with one key. Is it possible to save the Usernames in an array so that I can list them later ? I think it actually overwrites itself..
//Saving the username from input field to the Local Storage
top.username=document.getElementById("name").value;
localStorage.setItem('user', top.username);
//Getting out the username from the Local Storage
document.getElementById('list').innerHTML =localStorage.getItem('user');
Thanks for your help!
You can do something like this:
localStorage.setItem('arrayOfUserNames', JSON.stringify(['foo']))
var arrayOfUserNames = JSON.parse(localStorage.getItem('arrayOfUserNames'))
arrayOfUserNames.push('bar')
localStorage.setItem('arrayOfUserNames', JSON.stringify(arrayOfUserNames))
arrayOfUserNames = JSON.parse(localStorage.getItem('arrayOfUserNames'))
console.log(arrayOfUserNames) // ["foo", "bar"]
You can do something like this:
let loginForm = this.loginForm.value;
localStorage.setItem('userName', JSON.stringify([loginForm.userName]));
localStorage.setItem('password', JSON.stringify([loginForm.password]));
Related
How to save user data in localstorage even after refreshing
localStorage.setItem('bas',JSON.stringify(basketList));
const objectorage = JSON.parse(localStorage.getItem('object'));
Which command is more correct for storage?
This command localStorage.setItem('bas',JSON.stringify(basketList)); use to save data to localStorage with key is bas.
And this command localStorage.getItem('bas') is get data from localStorage with key is bas.
localStorage storage string data. So you get data from localStorage, you need parse it to object using JSON.parse(localStorage.getItem('bas'));.
Hope this help!
Your code seems ok.
To save a new object in localstorage use:
localStorage.setItem('userData', JSON.stringify(userData));
To get an existing object in localstorage use:
const myuserdata = JSON.parse(localStorage.getItem('userData'));
For more info check
setItem
getItem
Which command is more correct for storage?
None of them is "more correct" than the other. They are two different commands with different purposes:
localStorage.setItem(keyName, keyValue) stores data in the local storage under the provided keyName.
localStorage.getItem(keyName) retrieves the value stored under the provided keyName.
So, in your code:
localStorage.setItem('bas',JSON.stringify(basketList));
const objectorage = JSON.parse(localStorage.getItem('object'));
The first command stores the stringified basketList under the key bas. The second command tries to get the value stored under the key object, which doesn't exist in this case. The second command should instead be:
const objectorage = JSON.parse(localStorage.getItem('bas'));
According to Geeksforgeeks, localStorage has no expiration time.
You can test it with these steps:
Set an Item
basketList = ['a','b']; localStorage.setItem('bas',JSON.stringify(basketList));
Refresh it and print the value
JSON.parse(localStorage.getItem('bas'));
https://www.geeksforgeeks.org/localstorage-and-sessionstorage-web-storage-apis/#:~:text=LocalStorage%20has%20no%20expiration%20time,the%20user%20manually%20delete%20it.
I have a problem to get the specific value of my key.
I created the array "UserLoggingData" (key) with the values of 'password','email' and 'id' (Time Stamp)
that are stored in the object User and saved in the local storage.
The parameters email and password are taken from a form.
let login_data =[];
const addUser = (ev)=>{
ev.preventDefault();
let user = {
id : Date.now(),
email:document.getElementById('email').value,
password:document.getElementById('password').value
}
login_data.push(user);
document.forms[0].reset();
console.log(login_data);
//save to local storage
localStorage.setItem('UsersLoggingData',JSON.stringify(login_data));
Then I get such result in Local Storage:
How do I get to the specific password or email? How can I display them or get them so I can operate on them afterwards?
I tried localStorage.getItem('UserLoggingData')
but it shows null.
I need this for my diploma thesis so thanks for help in advance!
You have to parse the string you will get from localStorage.getItem(). Once you've done this you will have an array (based on your screenshot). This code should log the first email in your console :
const data = JSON.parse(localStorage.getItem(UsersLoggingData));
console.log(data[0].email)
I need to store the email of a logged in user, which I have stored into
sessionStorage with the line of code:
sessionStorage.setItem("loggedInUser", $("#email").val());
But in a different program, I need to store the email as something so that it can be sorted and posted to a php file that inserts it into my database. Here is my javascript so far.
$(document).ready(function () {
//When the submit button on the recruitment form is pressed.
$("#SubmitRecruit").on("click", function () {
//store each individual entry into a separate variable.
var email = sessionStorage.loggedInUser;
var forename = document.getElementById("forename").value;
var surname = document.getElementById("surname").value;
var jobType = document.getElementById("jobType").value;
var phoneNo = document.getElementById("phoneNo").value;
//create an array with the details in.
var recruitdetail = {
email: email,
forename: forename,
surname: surname,
password: password,
phoneNo: phoneNo,
}
//log the forename in the console so that we know that the register has been successful.
console.log(email)
//direct the user to the login page and alert them that their registration was successful.
window.location.href = "../index.html"
alert("Your recruitment post was made, thank you. We will get back to you shortly.")
//posts the JSON object to the php file so it can fill the database, and converts the register array into JSON so it can be read.
var jqxhr = $.post("../php/recruit.php", JSON.stringify(recruitdetail)
)
}
})
On the 5th line I tried to make it equal to sessionStorage.loggedInUser with no avail. I know I need to store email as something from session surely, as then it will be passed back into php and stored in db, but I cannot figure out what or how to do this. Any help will be greatly appreciated.
In order to use local storage with our array, we'll need to convert our array into a string using a method that makes it easy for us to unconvert later. The way convert an array into a string is by using the JSON stringify function.
Let's say you have the following array called movies:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
Using the stringify function, your movies array can be turned into a string by using the following syntax:
JSON.stringify(movies)
Since we want to store everything into our local storage, when you put it all together, you get the following:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
localStorage.setItem("quentinTarantino", JSON.stringify(movies));
To get the item from session storage try using the getItem method:
var email = sessionStorage.getItem("loggedInUser");
See sessionStorage documentation.
For the ajax request, just pass the object directly to $.post and put the alert in the success callback so it only shows when the request completes successfully:
//posts the JSON object to the php file so it can fill the database, and converts the register array into JSON so it can be read.
var jqxhr = $.post("../php/recruit.php", recruitdetail, function(data) {
alert("Your recruitment post was made, thank you. We will get back to you shortly.")
});
As a side note - if you have a table of users/logins, the email of each user should stored in that table. The foreign key between your users table and other tables would then be an (auto-incrementing) ID, rather than an email address. This makes the system much more flexible (email can be changed, etc).
If by different program you mean different application on different domain, then you can try sending the email value through an AJAX request to be stored in the PHP session.
If on the same domain but just a different app running in a different tab, then you can use localStorage, with the same syntax as sessionStorage. Note that sessionStorage data is limited to the tab in which it was set.
localStorage.setItem("loggedInUser", $("#email").val());
and then
var email = localStorage.loggedInUser;
Or you can use cookies.
https://www.w3schools.com/js/js_cookies.asp
I have used the 'prompt' method into asking for a character name. however i am wandering if i can save that data to then use again in different html documents, to use the characters name in context. I am currently using Javascript and would like to try and use that to solve this issue.
You can use localStorage to access the data input by user on another page (must be same origin).
var value = prompt('Please enter your name');
if (value) {
localStorage.setItem('username', value);
}
To get the saved data on another page, use:
localStorage.getItem('username');
Just assign a variable prompt function. The user input will be saved in this variable.
var saveMe = prompt('What time is it?')
console.log (saveMe)
If you want to store data and use them only locally you should maybe use the local storage, this allow you to save data into the user's browser. But you should know that old browsers do not support that.
Look at the W3School class about local storage.
Here is an example of how it works :
localStorage.setItem("userName", prompt('Your name'));
And then when you need to access it :
localStorage.getItem("lastname");
I'm using Lawnchair, and I've managed to store a value locally. Something like this:
var Users = new Lawnchair({table:'Users', adaptor:'dom'});
function save_prompt()
{
var UserName = prompt("Your Username","John Doe");
if (UserName!=null && UserName!="")
{
Users.save
({key:'UserData', SavedUserName:UserName});
}
}
function recall_prompt()
{
Users.get
('UserData',function(r)
{
document.getElementById('Message').innerHTML = r.SavedUserName;
}
);
}
I call both functions save_prompt & recall_prompt using buttons binded with onclick.
Basically this script will pop up a textfield to enter your username (John Doe is default) and saves it.
With recall_prompt, it worked fine by showing the saved username in the html div id="Message".
My question is, how to save a second, third, and beyond usernames? And how to retrieve them all to show in the html div? I've tried numerous methods that can be found on the 'net but I just can't get it to work. It seems the new username always overwrites the old ones.
Lawnchair saves data as Key:value pairs. So if u save another username with the same key, (UserData), it'll always get overridden. To save more usernames u'll have to change the keys. Make it UserData_1, UserData_2, like that.
Or you could store an array of usernames with the key 'UserData', so each time u need to save a username, get the array from DB, then add the new username to it and resave it.