Storing and Retrieving User Input - javascript

How to store user input from multiple pages and retrieve/display back user data on another html page
I am making a voting system and I needed help storing my results. Currently using local storage in JavaScript. Please do not recommended using data base as the deadline for the project is in 4 days.
So the main problem is whenever a user enters his/her preferences for a candidate the preferences are directly stored on another html page, but as soon as the second user enters his/her preferences the preferences by the first candidate disappears and the preferences for the second candidate gets stored.
I need to store preferences from every user to the html page. I need a efficient way to store my results in.
My local storage code
//store//
localStorage.setItem("preference1", selection[i].value);
// retrieve //
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
document.getElementById('display').innerHTML += `${key}: ${value} <br>`;
}

This answer is covering how you can add multiple "sets" of data to local storage (it is not secure and only works for a single browser):
Build an object containing all of the preferences for the current user
Push these into an array that will be stored in local storage
When saving the array, use JSON.stringify to convert the array to a string
When retrieving the array (as a string), convert it back using JSON.parse
(As localstorage is not allowed inside stack snippets, check this identical JSFiddle to see it working)
// Keeping your key in a variable is generally good practice
// so it's easy to change and immune to typos
const localStorageKey = 'preferences'
function addNew() {
// Build an object containing all the prefernces for the current user
var preferences = {
a: 'A',
b: 'B',
c: 'C',
}
// Load the existing data
var existingData = load()
// Push the new users data to the data
existingData.push(preferences)
// Save the data
save(existingData)
}
function load() {
// Get the saved data from local storage
var existing = localStorage.getItem(localStorageKey)
if (existing) {
// If the data exists, parse it back into an array
existing = JSON.parse(existing)
} else {
// If this is the first time, create an empty array
existing = []
}
// Return the array with any previous data included
return existing
}
function save(data) {
// Save data to local storage, converting the JS array to a string first
localStorage.setItem(localStorageKey, JSON.stringify(data))
}
// Adding events to the example buttons
document.getElementById("example1").onclick = addNew
document.getElementById("example2").onclick = function() {
var currentSave = load()
console.log(currentSave)
}
<button id="example1">Add new users data</button>
<button id="example2">Print out currently saved data</button>

Related

Todo List with JavaScript and make remain on browser even after you refresh

I built a Todolist with JavaScript its working fine but I want my Todo-items to remain on the browser even if I refresh till I delete it. What can I do?
There are 2 ways to go about this
The common approach - get a backend service up and running, then store it in a database so that it can be fetched anytime from any device.
The browser only approach - If you are looking for a simple enough approach, you may use the localStorage API and implement localStorage.setItem(), localStorage.getItem() and localStorage.removeItem() methods to save your todos locally on the users machine. Do note that this data can be cleared by the user.
To know more about when localStorage is cleared, refer this When is localStorage cleared?
This solution uses LocalStorage to persist data across browser reloads.
Refer to in-code comments for guidance, particularly about tracking the state of your data in JavaScript, and syncing that state with both the UI and the persistent (stored) data.
Limitations:
The "ToDo" items in this demo have only a single property, a 'description'.
The UI only allows adding items (by typing a description and tabbing
or clicking out of the input).
The code runs correctly in Chrome, although NOT in the Stack Overflow snippet due to sandboxing.
<h3>Todo</h3>
<input id="newitem" />
<div id="list"></div>
<script>
// Names HTML elements, calls `makeAndAddNewItem` when input changes
const
newItemInput = document.getElementById("newitem"),
listDiv = document.getElementById("list");
newItemInput.addEventListener("change", makeAndAddNewItem);
// `tempList` is an array containing all our list items,
// serving as the Source of Truth for the state of our data.
// When it changes, we should update the page and the stored list
//
// On page load, we retrieve data from storage and update the page
const tempList = getListFromStorage();
showListOnPage(tempList);
function getListFromStorage(){ // Called on page load
// Gets the storedList (if any), converts it to an array
// and returns the array (or returns an empty array)
const storedList = localStorage.getItem("list");
const list = storedList ? JSON.parse(storedList) : [];
return list;
}
function showListOnPage(tempList){ // Called on page load
// Loops through the tempList array and adds each item to the page
for(let currentItem of tempList){
showItemOnPage(currentItem);
}
}
function showItemOnPage(item){ // Used on load and for new items
// Appends to the listDiv a new `p` element, whose content
// is the value of the `description` property of the item
let
descriptionNode = document.createTextNode(item.description),
newParagraph = document.createElement("p");
newParagraph.appendChild(descriptionNode);
listDiv.appendChild(newParagraph);
}
function makeAndAddNewItem(event){ // eventListener for new items
// Makes a `newItem` object whose `description` property
// comes from the value of the `newItemInput` element
// Adds the new item to the page and to the tempList
// Replaces the stored list, using the newly changed tempList
const newItem = {};
newItem.description = newItemInput.value;
newItemInput.value = ""; // Clears input
tempList.push(newItem); // Updates list
showItemOnPage(newItem); // Updates page
updateLocalStorage(tempList); // Updates storage
}
function updateLocalStorage(){ // Called when tempList changes
// Converts tempList (array) to a string to update localStorage.list
const listToStore = JSON.stringify(tempList);
localStorage.setItem("list", listToStore);
}
</script>

How to set or get JavaScript multiple cookies based on html ids?

I made a blog application which has many articles. I want to set cookies for articles which user click . So that user can see which articles he/she visited or read. I am not storing cookies on backend. Cookies are set based on articles id
first of all welcome to StackOverflow
From your question, you can even leverage the localStorage for that no? There's no point to use only Cookies, but all you would need to do is:
for each page reload, append that page to an Array
if you want to get that value, read the array
with time, you would want to add a couple more things
only store the last 10 visited pages (so you don't end up with 100 links)
don't repeat pages
adding to localStorage is a bit simpler than cookies, as you can just do window.localStorage.setItem(key, payload)...
and you would read as var links = window.localStorage.getItem(key)
remember that, just like cookies, you need to save as a string, doing .setItem('links', { a: 1 }) will endup saving [Object Object]
if you have something like:
var linksStorage = {
KEY: 'visitedLinks',
get: () => {
var allLinks = window.localStorage.getItem(this.KEY)
return JSON.parse(allLinks || '[]') // parse string or start with empty array
},
savePage: () => {
var allLinks = this.localStorage.get() // get all existing links
allLinks.push({ // append this page info
id: window.location.query,
page: window.location.pathname
})
window.localStorage.setItem(
this.KEY, JSON.stringify(allLinks)) // save back
}
}
then a simple:
window.linksStorage.savePage()
will append the current page to the list, and when you need to read:
window.linksStorage.get()
will give you the list as an Array object
Added after comments
var writeCookies = () => {
var allCookies = window.document.cookie.split('; ') // split them all
document.write("<ul>")
allCookies.forEach(c => { // for each cookie
var info = c.split('=') // name and value
document.write(`<li><b>${info[0]}</b> -> ${info[1]}`)
})
document.write("</ul>")
}
and execute as writeCookies()

How to set Firebase snapshot data into array in sessionStorage

var db1 = firebase.firestore();//API firestore database
var docRef1 = db1.collection("SuccessTransaction");
var showSeat = docRef1.get().then(function(snapshot){
snapshot.forEach(function(doc){
if(doc.exists){
alert(doc.data().Seat);
sessionStorage.setItem("routeUnavailableSeat", JSON.stringify(doc.data().Seat));
}else{
alert("No such documet!");
}
});
}).catch(function(error){
alert("Error getting document!", error);
});
I had a problem with this kind of situation. My intention was to set my snapshot value and set it into sessionStorage. The problem is after the system run, it will replace the old data and replace the new data. How can I using array or other method in order to keep all my data in sessionStorage?
The local storage API (that session storage is based on) can only store string values. So to store your values as an array, you will need to encode the array in a string.
Aside from that, it's a matter of getting the current value, parsing it, and then adding it back into session storage:
if(doc.exists){
let value = sessionStorage.getItem("routeUnavailableSeat");
let seats = current ? JSON.parse(current) : [];
seats.push(doc.data().Seat)
sessionStorage.setItem("routeUnavailableSeat", seats);
}

Retain multiple fileEntries with chrome filesystem API?

How can I retain multiple fileEntry objects to reuse when the user opens the app with the chrome filesystem API? I've tried to use arrays to store the file entries and it works fine up until I restart the app and can't use them. Instead of returning a fileEntry object the console returns an object object (this is after I used chrome.storage.local.set and chrome.storage.local.get to set and retrieve the entries once the user restarted the app.)
You cannot persist the actual file entries between sessions. You need to use chrome.fileSystem.retainEntry which will return an id, which you can store, and then use chrome.fileSystem.restoreEntry to regain access to the entry when the app is re-opened.
After a lot of back and forth, I figured out how to retain multiple fileEntries.
Here's the code for the people who need it.
//save
//'fileEntries' is an array that I made earlier where multiple entries were stored
var keep = [];
fileEntries.forEach(function(entry, index) {
//if it's empty or null, return nothing
//otherwise add the id to our empty array 'keep'
if (entry == null) {
//do nothing
} else {
keep[index] = chrome.fileSystem.retainEntry(entry);
}
});
chrome.storage.local.set({
retained: keep
});
//load
chrome.storage.local.get('retained', function(data) {
var retained = data.retained;
retained = retained.filter(function(d) {
return d
});
for (var i = 0; i < retained.length; i++) {
var tab = retained[i];
chrome.fileSystem.restoreEntry(tab, function(entry) {
fileEntries.push(entry);
});
}
});
And.... thats about it! When the loading function is done, the fileEntries array, has all the fileEntry objects!

Adding to existing Firebase integer

Is it possible to add to an existing integer stored in firebase. I am building an application that keeps track of a users word count by storing a key in their userId firebase key called wordCount:. I'm able to successfully update that key when the user clicks a button called "marked as read" but unfortunately it just replaces the integer instead of adding to it. Is it possible to get it to add to the value of the key wordCount: rather than replacing it.
Here is the code inside one of my controllers. Side note, angularAuth.getAuth just checks to see if the user is logged in or not
this.markedAsRead = function(wordCount){
if(angularAuth.getAuth){
var userBase = new Firebase('https://readyread.firebaseio.com/users/'+angularAuth.getAuth.uid)
userBase.update({
wordsRead: wordCount
})
}else{
console.log('please log in to use this feature')
} }
I was able to get it thanks to an idea of #manube
this.markedAsRead = function(words){
var userBase = $firebaseObject(new Firebase('https://readyread.firebaseio.com/users/'+angularAuth.getAuth.uid))
var users = new Firebase('https://readyread.firebaseio.com/users/'+angularAuth.getAuth.uid)
userBase.$loaded().then(function(data){
self.count = data.wordsRead
users.update({
wordsRead: self.count+words
})
})}

Categories

Resources