Store values in javascript session and access it when required - javascript

I am working on a project where there is no user login system where people come and select multiple events they want to be in. From javascript, I wrote a code where if a user clicks it will store the id of an event in a javascript array but when I go to the checkout page the data gets cleared. So I came up with the idea of using localstorage of javascript. I have reached here:
var myData = '';
var livalue = [];
$('.party_a').on('click', function(e){
alert('One item added to the cart!');
sessionStorage.setItem("livalue", $(this).val());
alert(localStorage.getItem("livalue"));
myData = partyName.length;
if(myData == 1){
$('#cart').html("<li><a href='{{ route('checkout') }}'>My Cart<sup id='cart_number'></sup></a></li>");
}
$('#cart_number').html(myData);
});
But when I try to alert the livalue, it gives me null. Any suggestion on this matter is appreciated.

Related

how to save state of the page when refreshing? (HTML, JS)

(DISCLAIMER: I'm new to coding so my code probably isn't optimal. If you know a better way to do it, feel free to leave it in the comments )
Most of the time I had no idea what I was doing, but with patience and with you guys' help I came up with this:
if (window.localStorage) {
// Create the Key/Value
var cNum = localStorage.getItem("currentNumber");
if (localStorage.currentNumber == undefined) {
localStorage.setItem("currentNumber","0");}
// Variables
resetCount.innerHTML = localStorage.currentNumber;
// Functions
function btnR() {
cNum++;
localStorage.currentNumber = cNum;
resetCount.innerHTML = cNum;}}
else { console.log("No"); }
HTML:
<button id="resetButton" onclick="btnR()">Reset</button>
<p id="resetCount">0</p>
I was creating a button that each time you click on it, it reset the checkboxes, but I also wanted a counter to see how many times they got rested. The problem was that every time I click the button the counter also reset. Now that is solved I can try to apply the same thing for the checkboxes, so they don't reset on refresh either.
Note: I had to put the .SetItem in an if statement cause, even tho the value was in storage it kept setting back the value to zero every time I refreshed the page. This was the way I found to stop that.
You either need to set up a back end to send data to and save the information you want to keep stored, or save data in localStorage.
Just know it is not the best practice to save sensitive info in localStorage (as they can be compromised in cross-site scripting attacks).
localStorage.setItem puts a bit of data into localStorage (and that stays there till you clear it) and localStorage.getData extracts it.
This might help get you started on localStorage, but you will have to figure out the function to set the colour to the element you have.
let boxColour = localStorage.getItem("boxColour");
if (boxColour === null) {
setBoxColour("colour");
} else {
setBoxColour(boxColour);
}
function setBoxColour(colour){ localStorage.setItem("colour");}
/* Inside the function you have to get the item and change it's style attribute or add a class to add styles */
Careful with that localStorage data!
You could use LocalStorage.
It saves data in the page to be used after when the page is refreshed or closed and opened later.
Theres a example:
(Unfortunally, it seems to not work in the stackoverflow site, but if you try at your HTML file it will work)
var loadFunc = (elem) => {
console.log("Value saved is: "+ localStorage.getItem("savedValue"));
if(localStorage.getItem("savedValue")){ //checks if value is saved or not
elem.checked = localStorage.getItem("savedValue");
}
}
var clickFunc = (elem) => {
localStorage.setItem("savedValue", elem.checked); //set te value if in localStorage
}
Click the checkbox and the value will be saved.
<input type="checkbox" onload="loadFunc(this)" onclick="clickFunc(this)">

Html Storage resets every refresh, initialize function not working

For a website I am working on, I am trying to keep information on how many items you buy to be shown across html pages. Researching how to do this has led me to believe that Html sessionStorage is the best way to do this (if there is a better/easier way please let me know). Yet, whenever I refresh the html page or go to another page the data resets.
Here is my code:
function initialize(name, val) {
if(localStorage.getItem(name) === null) {
localStorage.setItem(name, val);
}
}
initialize("subCost", 0);
initialize("quantity", 0);
initialize("hasProduct", false);
Then since the storage only stores strings, I convert these into integers and boolean
var $quantity = parseInt(localStorage.quantity);
var $subCost = parseInt(localStorage.subCost);
var $hasProduct = localStorage.hasProduct == "true";
Before without the initialize function, I made the local storages items like this
localStorage.setItem("subCost", 0);
localStorage.setItem("quantity", 0);
localStorage.setItem("hasProduct", false);
and still converted these into those variable but they never saved with each refresh. How do I get these to save changes I make to them with each refresh.
The .setItem() method on localStorage doesn't only "sets" a "memory placeholder" for a value... It also overwrites it, if it already exist.
To save the user generated values, the best "moment" to save a "change" is the change event.
Use the same .setItem() method as in your initialize() function.
$("input").on("change",function(){
// Get id and value.
var id = $(this).attr("id");
var value = $(this).val();
// Save!
localStorage.setItem(id,value);
});
CodePen
Just as a hint...
This method to save values locally is ephemeral...
Values are kept until user closes the browser.
Not just closing the page, but closing the browser completely.
So to keep some values between pages navigated, this is the optimal use.
To store values for a longer run (like 6 months or longer), use cookies.
Have a look at jQuery Cookie plugin.

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

create and store user objects using localstorage

I am trying to create a user database using localStorage. I just need to store the created user with a unique id so I can reference it as a key later. Right now I have this code in my application.js:
$(document).ready(function() {
$("#signupform").submit(function(e) {
e.preventDefault();
var user = {
name: $('#pname').val(),
email: $('#email').val()
};
localStorage.setItem('user', JSON.stringify(user));
console.log(JSON.parse(localStorage.getItem('user')).name);
var html = new EJS({url: 'templates/usershow.ejs'}).render(user);
var content = document.getElementById('content');
content.innerHTML = content.innerHTML + html;
$("#signupform").remove();
});
});
I need localStorage.setItem('user'... to be something like localStorage.setItem('i'... where "i" increments with each newly created user (like an index) when the submit button is clicked. Would it make more sense to use the user email as the key? That way I can look up each user by their email? How would I go about doing this? Again...I am just trying to set up a user database where I can easily reference users and their info using localStorage. Show me how!
I'd go about incrementing an ID by storing a nextUniqueId in localStorage, then grab that for the key and increment it. Something like this:
function getNextUnique () {
var next = localStorage.getItem('nextUniqueId');
next = next ? parseInt(next) : 0;
var newNext = next + 1;
localStorage.setItem('nextUniqueId', newNext);
return next;
}
Call it whenever you want to save a new user:
localStorage.setItem(getNextUnique(), JSON.stringify(user));
It makes more sense to use the user's email. Simplicity is good.
BUT... this is localStorage. There shouldn't ever be more than one user using it, right? localStorage itself is unique to the client application. Are there really going to be multiple users using the same browser?
If so, then this is fine. But i wonder if you are really thinking about how localStorage works...

JavaScript list saving question

I have this fiddle: http://jsfiddle.net/y8Uju/5/
I am trying to save the numbers, because, when I submit, the list of numbers gets erased. I am a little new to JavaScript so am not quite familiar to what is available. In PHP I would use sessions to save the list, but what can I do in JavaScript to do this?
Here is the JavaScript code:
function bindName() {
var inputNames = document.getElementById("names").getElementsByTagName("input");
for (i = 0; i < inputNames.length; i++) {
inputNames[i].onkeydown = function() {
if (this.value == "") {
setTimeout(deletename(this), 1000);
}
}
}
}
document.getElementById("addName").onclick = function() {
var num1 = document.getElementById("name");
var myRegEx = /^[0-9]{10}$/;
var itemsToTest = num1.value;
if (myRegEx.test(itemsToTest)) {
var form1 = document.getElementById("names");
var nameOfnames = form1.getElementsByClassName("inputNames").length;
var newGuy1 = document.createElement("input");
newGuy1.setAttribute("class", "inputNames");
newGuy1.setAttribute("id", nameOfnames);
newGuy1.setAttribute("type", "text");
newGuy1.setAttribute("value", num1.value);
form1.appendChild(newGuy1);
num1.value = "";
bindName();
}
else {
alert('error');
}
};
function deletename(name) {
if (name.value == "") {
document.getElementById("names").removeChild(name);
}
}
You can use localStorage: http://jsfiddle.net/y8Uju/8/
Loading:
var saved = JSON.parse(localStorage["numbers"] || "[]");
for(var i = 0; i < saved.length; i++) {
document.getElementById("name").value = saved[i];
add(false);
}
Saving:
var saved = JSON.parse(localStorage["numbers"] || "[]");
saved.push(num1.value);
localStorage["numbers"] = JSON.stringify(saved);
And define the function of the addName button separately, so that you can call it when loading as well.
Edit: You have to execute a function when the page is loading to fetch the stored numbers, and add some code to save the entered number when one clicks the Add button.
For storing you can use localStorage, but this only accepts Strings. To convert an array (an array containing the entered numbers), you can use JSON.
When loading, you need to add the numbers just like happens when the user fills them in. So you can set the name input box value to the saved number for each element in the array, and then simulate a click on the Add button.
So you need an add function that is executed when:
User clicks Add button
Page is loaded
However, when simulating the click the numbers should not get stored again. You need to distinguish between a real click and a simulated one. You can accomplish this by adding an argument to the add function which represents whether or not to store.
Not entirely sure what the question is, but one problem I see with the code - id's can't be numbers, or start with numbers
var nameOfnames = form1.getElementsByClassName("inputNames").length;
//....
newGuy1.setAttribute("id", nameOfnames);
That might be slowing you down somewhat. Perhaps set id to 'newguy' + nameOfnames
Jeff, the reason that the page keeps getting erased is because the form submission triggers a page reload. You need to place a listener on the form submit event and then send the data through AJAX. This way the data is POSTed to "text.php" without reloading the page with the form.
You could place the values in a cookie but that is not ideal because you have a fairly limited amount of space to work with (4kb). I also get the feeling that you're trying to hand them off to some server side script so HTML5 local storge wouldnt be a good solution, not to mention that your eliminating over half of the people on the internet from using your site that way.
Since browsers are inconsistent in how they attach event listeners AND how they make AJAX requests. I think that most people would recommend that you use a library like jQuery, dojo, or prototype which abstract the process into one function that works in all browsers. (my personal fav is jQuery)
There are a few options available to you:
Save it client side using cookies (http://www.quirksmode.org/js/cookies.html)
Save it client side using HTML5 local storage (http://diveintohtml5.ep.io/storage.html)
Save it server-side using Ajax
The Ajax solution involves a server side page (in PHP for example) that reads a request (a POST request for example) and saves it into a database or other. You then query that page in JavaScript using XmlHTTPRequest or your favorite library.

Categories

Resources