local storage items after refresh page - javascript

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction();">Fav Number</button>
<div id="result"></div>
<!--This code works on chrome-->
<script>
function myFunction() {
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
var a = prompt("fav number");
localStorage.setItem("lastname", a);
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
</script>
</body>
</html>
hello,
is it possible to get local storage items back when you refresh the page?
and if so, how?
Thanks
Dylan,

Getting and setting localStoragedata. In following example the data to set is a Object (which is handled by JSON.stringify). If need to persist a string / intthere is no need in using JSON.stringify.
var dataObject = { 'item1': 1, 'item2': 2, 'item3': 3 };
// Set localStorage item
localStorage.setItem('dataObject', JSON.stringify(dataObject));
// Retrieve the object from localStorage
var retrievedObject = localStorage.getItem('dataObject');
// console.log retrieved item
console.log('retrieved data Object: ', JSON.parse(retrievedObject));
By getting localStorage data when needed, there no need to handle the page refresh part. The localStorage data is fetched when needed by application functions and logics.

Related

Saving checkboxes asynchronously in Google Apps Script

I'm new to asynchronous calls and I think this is the problem. However, i'm not too sure how to fix it since Google Apps Script does not support promises and I also don't know how to use them. I've heard that if HTML Service is used in GAS, then promises are possible and this is what I'm using. However, I'm at a loss on how to implement this. Here is what I have so far. The main PROBLEM IS THAT I need the data to show in the second Logger.log on the server-side (code.gs) below. The data gets to the function in the first logger.log (code.gs), but then the object is empty (not null), when displaying the user cache in the second logger.log (code.gs). Any keys/data can be used and problem can be replicated, so it has something to do with asynchronous calls, but how do I fix it in the GUI_JS code?
Server-side (code.gs):
// global variable to save into the cache
var userCache = CacheService.getUserCache();
// SAVE OPERATION - saves the checkboxes into the user cache
function processSavedValues(checkboxesObj){
Logger.log(checkboxesObj); // this line shows in Logger
userCache.putAll(checkboxesObj, 20);
var getCache = userCache.getAll(['key1','key2']);
Logger.log(getCache); // this line doesn't show in Logger
}
// Loads the HTML Service of Apps Script
function doGet(request) {
return HtmlService.createTemplateFromFile('index').evaluate();
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
Client-side (index.html):
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
<fieldset class="columnList">
<div>
<input type="checkbox" id="key1" name="fieldset[]" value="value1">
<label class="checkmark" for="key1">test1</label>
</div>
<div>
<input type="checkbox" id="key2" name="fieldset[]" value="value2">
<label class="checkmark" for="key2">test2</label>
</div>
</fieldset>
</form>
<button onclick="saveAllCheckboxValues()">test</button>
<?!= include('GUI_JS'); ?>
</body>
</html>
Client-side using HTML Service (GUI_JS.html):
<script>
// Saves all checkbox values into the cache
function saveAllCheckboxValues(){
// Select all checkboxes in the document
var allCheckboxes = document.querySelectorAll("input[type=checkbox]");
// Create a Key/Value pairs with the IDs and values of each checkbox
var checkboxesObj = {};
for (var i = 0; i < allCheckboxes.length; i++) {
checkboxesObj[allCheckboxes[i].id] = allCheckboxes[i].checked;
}
// sends the checkbox values server-side into the cache
google.script.run.withSuccessHandler(checkboxSaved).processSavedValues(checkboxesObj);
// displays successfully saved
function checkboxSaved(){
alert("Great Success!");
}
}
</script>
The result of Logger.log:
[19-03-14 18:28:38:913 PDT] {key1=true, key2=true}
[19-03-14 18:28:38:959 PDT] {}
I think that the reason of your issue is the boolean values in the object for putting to CacheService. At CacheService, the string value is used for putting. So how about this modification? Please think of this as just one of several answers. In my modification, the function of processSavedValues() was modified.
Modified script:
function processSavedValues(checkboxesObj){
Logger.log(checkboxesObj);
userCache.put("sampleKey", JSON.stringify(checkboxesObj), 20); // Modified
var getCache = userCache.get("sampleKey"); // Modified
getCache = JSON.parse(getCache); // Added
Logger.log(getCache);
}
References:
put(key, value)
get(key)
If this didn't work and this was not the result you want, I apologize.

Save Button-Click Count in localStorage in javascript

I made a button click counter for a website using some JavaScript.
The counter works well, but now I'm stuck in making the saving of the count. You know, if I click the button 3 times, the text says 3 Times. But I want to save that value so if the user refreshes the page, it should display 3 Times again.
I knew of using localStorage, I followed a simple tutorial and applied it to my code, but it does not seem to be working. When I run the page in Microsoft Edge and see the Debug page (F12), the console throws an error that says: Unable to get property 'getItem' of undefined or null reference. I searched in other posts but no one of these could solve my problem. It seems to be stuck when retrieving the value in localStorage.
This is my code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Increment count when button is clicked</title>
</head>
<body>
<input type="button" value="Registrar" id="countButton" />
<input id="ocityField" type="text" value="" placeholder="Ciudad de Origen"/>
<input id="cityField" type="text" value="" placeholder="Ciudad de participación"/>
<input id="name" type="text" value="" placeholder="Nombre"/>
<p>Personas Registradas: <span id="displayCount">0</span></p>
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
var textbox = document.getElementById("ocityField");
var textboxa = document.getElementById("cityField");
var textboxb = document.getElementById("name");
if(window.localStorage.getItem('count')){
var savedcount = window.localStorage.getItem('count');
count = window.localStorage.getItem('count');
}else{
count = 0;
}
display.innerHTML = count;
button.onclick = function(){
var mystring = textbox.value;
var mystring2 = textboxa.value;
var mystring3 = textboxb.value;
if(!mystring.match(/\S/) || !mystring2.match(/\S/) || !mystring3.match(/\S/)) {
alert ('Empty value is not allowed');
return false;
} else {
count++;
window.localStorage.setItem('count', count);
display.innerHTML = count;
textbox.value = "";
textboxa.value = "";
textboxb.value = "";
return true;
}
}
</script>
</body>
</html>
I tried using window.localStorage and just localStorage but no one did work.
May be that you use the IE browser does not support localStorage,The code can run in Chrome49.
Can I Use localStorage, here you can check what browser supports localStorage with version numbers.
Alternate way to store data on client side is cookies if localStorage doesn't supported by browser.
You can also use third party plugins like Modernizer, to check whether browser supports or not.
Modernizr.localstorage if it evaluate to true the browser supports localStorage.
Following example demonstrates localStorage and cookies depending on browser compatibility. uses Modernizer and jQuery
codepen

Raspberry button trigger Python script which should display in webpage

I have a Raspberry PI with a button attached to it.
I run a Python script on it to detect when the button is pressed.
When the button is pressed, it increment a number in a text file.
I need to display this number on a web page (Apache) and to launch a sound.
For the moment, my python script change the index.html with the value I need and I am using <meta http-equiv="refresh" content="1"> to resfresh the page.
The problem is that I need to know when the number is changing to launch the sound.
Too little information to say something concrete, but here's how I'd get around to it given the main following limitation that the page is not dynamic (no ajax).
General outline:
Put the value from the text file in a identifiable field like
<span id="myNumber">#the number from file goes here </span>
then on load with java script read the value of the field:
(planin JS)
var myNumberValue = document.getElementById('myNumber').innerHTML;
then create a cookie to store the last value on clinets machine:
document.cookie = "lastNumber="+myNumberValue;
To sum it all up: on loading the webpage launch a script that will :
check for a cookie
read a value from the coookie
(http://www.w3schools.com/js/js_cookies.asp)
read a value from the field
if a cookie exists compare the values and if the number
changed play a sound like here:
Playing audio with Javascript?
either way store the value from the field to the cookie for next
website update.
[Edit] Full working solution using local storage or cookies:
<html>
<head>
<META HTTP-EQUIV="refresh" CONTENT="5">
<script type="text/JavaScript">
function myFunction()
{
var numberDisplayed = parseInt(document.getElementById('myNumber').innerHTML);
var numberInCookie = numberDisplayed;
//lets assume that's the only data in the cookie
var tmpData = readNumber();
if(tmpData!="NaN" && tmpData!= "undefined")
{
numberInCookie = tmpData;
}
if(numberDisplayed!=numberInCookie)
{
alert("changed to from "+ numberInCookie+" to " + numberDisplayed);
}
saveNumber(numberDisplayed);
}
function readNumber()
{
if (typeof(Storage) !== "undefined") {
return localStorage.getItem("lastNumber")
} else {
var cookieData = document.cookie;
//lets assume that's the only data in the cookie
var tmpData = parseInt(cookieData.split("=")[1]);
return tmpData
}
}
function saveNumber(number)
{
if (typeof(Storage) !== "undefined") {
localStorage.setItem("lastNumber", number);
} else {
document.cookie = "lastNumber="+number;
}
}
</script>
</head>
<body onload="myFunction()">
<span id="myNumber">2</span>
</body>
</html>
[Edit 2] as the author of the question hinted he doesn't actually want to use the site refresh here's another option:
lest start a loop that will load a test file from the server as an ajax request. then the data is loaded, parsed, store it loacally as before. and set timer to trigger the refresh again.
One importatnt thing the files need to be available on the same domain / server (see HTTP access control (CORS) for more information)
<html>
<head>
<script type="text/JavaScript">
var externalNumber = 0;
var timer;
function myFunction()
{
// start the readouts:
LoadExternalData();
}
function LoadExternalData()
{
var client = new XMLHttpRequest();
client.open("GET", "http:/myserver/readme.txt");
client.onreadystatechange = function() {
externalNumber = parseInt(responseText);
//store a local copy
var NewestNumber = externalNumber;
var tmpData = readNumber();
if(tmpData!="NaN" && tmpData!= "undefined")
{
numberInCookie = tmpData;
}
if(NewestNumber!=numberInCookie)
{
alert("changed to from current "+ numberInCookie+" to " + NewestNumber);
}
saveNumber(NewestNumber);
timer = setTimeout(LoadExternalData, 1000);
}
client.send();
}
function readNumber()
{
if (typeof(Storage) !== "undefined") {
return localStorage.getItem("lastNumber")
} else {
var cookieData = document.cookie;
//lets assume that is the only data in the cookie
var tmpData = parseInt(cookieData.split("=")[1]);
return tmpData
}
}
function saveNumber(number)
{
if (typeof(Storage) !== "undefined") {
localStorage.setItem("lastNumber", number);
} else {
document.cookie = "lastNumber="+number;
}
}
</script>
</head>
<body onload="myFunction()">
<span id="myNumber">2</span>
</body>
</html>

Using jQuery for setting Local Storage Keys from Input Value

So I'm trying to start on a to do list in html5 + jQuery using Local Storage, but for some odd reason I can't get the jQuery to make a local storage key.
Here is my code. I want it to collect the value of the input box, add it to local storage, and then print the code in the div named.
$('#taskEntryForm').submit(function () {
if ($('#taskInput').val() !== '') {
var input_value = $('#taskInput').val();
var stored_input = this.localStorage.setItem('task_',input_value);
var task = this.localStorage.getItem('task_');
$('#taskList').append("<br>"+task);
};
return false;
});
and then the HTML...
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="shit.js"></script>
</head>
<div id="cNew">
<form id="taskEntryForm">
<input id="taskInput" name="taskInput" autofocus></form>
</div>
<div id="taskList"></div>
</html>
In your code this stands for form. Local storage object is not part of the form, it is a part of window. You should change this (which represents form) to window, or remove this at all (because window.localStorage is identical to just localStorage):
$('#taskEntryForm').submit(function () {
if ($('#taskInput').val() !== '') {
var input_value = $('#taskInput').val();
var stored_input = localStorage.setItem('task_',input_value); // <- removed 'this'
var task = localStorage.getItem('task_'); // <- removed 'this'
$('#taskList').append("<br>"+task);
};
return false;
});
Here is a working jsFiddle

Passing a var to another page

Is it possible to pass the totalScore var to another page onclick so that it can be displayed there? ex: click submit link it goes to yourscore.html and display the score on page
$("#process").click(function() {
var totalScore = 0;
$(".targetKeep").each( function(i, tK) {
if (typeof($(tK).raty('score')) != "undefined") {
totalScore += $(tK).raty('score');
}
});
alert("Total Score = "+totalScore);
});
Let we suppose that your HTML may be as follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#process").click(function() {
var totalScore = 0;
/*
Your code to calculate Total Score
Remove the next line in real code.
*/
totalScore = 55; //Remove this
alert("Total Score = "+totalScore);
$("#submit-link").attr('href',"http://example.com/yourscore.html?totalScore="+totalScore);
});
});
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<button id="process">Process</button>
<br />
Submit Total Score
</body>
</html>
Check out this DEMO
In yourscore.html you may able to know more in the following queation to extract the URL parameter from the URL:
Parse URL with jquery/ javascript?
This is generally done by changing the url of the page. i.e. if you are going go to a new page, just do:
http://example.com/new/page?param1=test
If the page already exists in a new window (like a popup that you own), set the url to something new:
http://example.com/new/page#param
Open a window:
var win = window.open('http://example.com/new/page?totalscore'+totalscore,'window');
Change the location:
win.location.href='http://example.com/new/page?totalscore'+totalscore;
Other ways of doing this could be websockets or cookies or localstorage in HTML5.
if you are aiming to support more modern browsers the elegant solution could be to use sessionStorage or localStorage! Its extremely simple and can be cleared and set as you need it. The maximum size at the low end is 2mb but if your only storing INTs then you should be okay.
DOCS:
http://www.html5rocks.com/en/features/storage
http://dev.w3.org/html5/webstorage/
DEMO:
http://html5demos.com/storage
EXAMPLE:
addEvent(document.querySelector('#local'), 'keyup', function () {
localStorage.setItem('value', this.value);
localStorage.setItem('timestamp', (new Date()).getTime());
//GO TO YOUR NEXT PAGEHERE
});

Categories