How to save things using Javascript - javascript

I am making a website where you can store financial things. Just for practise. Not to publice. So far I have making the part where you can add a new list. And fill in things. But of course if I refresh the page it will be gone. So how can I save the new made list?

You could store it in the Browser via a cookie or better, localStorage. But of course if the browser deletes the "personal data" or you use a different browser, the data is gone.
Normally you would set up a server (say, PHP) and save it in a database (e.g. MySQL), even if you use the application only on your own machine.

Try using cookies or WebStorage (localstorage or sessionstorage objects). And consider using HTTPS if you working with financial info

You could use Firebase. Works great if you're only doing small things.
Basically it allows you to store data online on their servers with the simple Firebase API.
Their tutorial should get you started:
Firebase 5 minute tutorial

I am very new to learning localstorage myself and since you said "storeing in the browser" , i guess the best comtemporary and hassle and hack free method is localstorage .
Here is a accordion i made which stores the state of the accordion(weather its open or closed).
FIDDLE HERE
JS ::
$(function () {
var initialCollapse = localStorage.collapse;
if (initialCollapse) initialCollapse = initialCollapse.split(",")
console.log(initialCollapse);
$(".collapse-headings>a").click(function () {
var div = $(this).parent();
div.toggleClass("close open");
$(".collapse-content", div).toggle("slow");
localStorage.collapse = $(".collapse-headings").map(function () {
return $(this).hasClass("open") ? "open" : "close"
}).get()
console.log(localStorage.collapse)
return false;
})
if (initialCollapse) {
$(".collapse-headings>a").each(function (i) {
var div = $(this).parent();
div.removeClass("close open").addClass(initialCollapse[i])
$(".collapse-content", div).toggle(initialCollapse[i] !== "close");
})
}
});
This might be a good starting point to understanding localstorge , but if you do a google search , you'll come across a ton of useful information such as cross browser compatibility and local storage limitation and fallbacks.

Related

localStorage not working in other host - javascript

I am developing a firefox addon. i use localStorage to save some data and retrieve.
function to check if it is available or not
if(!localStorage.getItem('font')) {
populateStorage();
}else{
var aValue = localStorage.getItem('font');
alert(aValue);
if not then create
function populateStorage(){
localStorage.setItem('cname', name);
localStorage.setItem('font', 'Helvetica');
localStorage.setItem('image', 'myCat.png');
}
This is perfectly working localhost but if i visit other host like google.com and try to get i am getting error not found
if(!localStorage.getItem('font')) {
alert('Not found !!!!');
}else{
var aValue = localStorage.getItem('font');
alert(aValue);
}
is there any way to fix this issue ? or am i doing it in wrong way ?
LocalStorage is intended to be accessible only from the same host. This allows different websites to have a different scope for their data, and also ensures that one website cannot access data from another website.
From MDN,
The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.
From: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
If you need to share data across different domains, you should use server-side persistence.
From what I've undestood local storage is not cross domain solution, so this behavior is correct.
What you need to do is fallow MDN solution. I've found something like this:
// define 2 objects
var monster = {
name: "Kraken",
tentacles: true,
eyeCount: 10
}
var kitten = {
name: "Moggy",
tentacles: false,
eyeCount: 2
}
// store the objects
browser.storage.local.set({kitten, monster})
.then(setItem, onError);
(code copied from MDN > JavaScript APIs > storage )
In this solution data will be pinned to browser/extension, not to domain. But be aware, that data still will be destroyed when user clear browser cache or something like that.

How to optimize $interval for real time notifications in Angularjs?

I am working on a social networking site. I have used following code to show the total notifications count in real time for a user.
Code:
function load_notifications(){
$http.get('http://localhost:3000/load').success(function(data){
$scope.totalNotify = data.total;
});
};
load_pictures();
$interval(function(){
load_notifications();
},300);
basically, this code checks the DB continuously at a given interval and if there is some change, it update the $scope value. But when I tried to check it with two different user in different browsers, it chokes the browser because of polling requests.
Is there any way to improve this method or have any other better alternative?
I am building my application using PHP and AngularJS. But I am open to other options for this module too.
This should be done using web sockets, not a polling ajax request.
JS: AngularJS and WebSockets beyond
PHP: How to create websockets server in PHP
Specifically, for web sockets using PHP, I would use Rachet.
A starting point for the PHP would be here: http://socketo.me/docs/hello-world
This hello world tutorial shows you basic javascript and PHP for interacting through Rachet.
awaitingResponse = false;
function load_notifications() {
if(!awaitingResponse) {
awaitingResponse = true;
$http.get('http://localhost:3000/load').then(function(response) {
$scope.totalNotify = response.data.total;
awaitingResponse = false;
}, function() {
awaitingResponse = false;
});
}
}
load_pictures();
$interval(load_notifications, 3000);
You could wait for 300 milliseconds after the answer was received, like this:
function load_notifications(){
$http.get('http://localhost:3000/load').success(function(data){
$scope.totalNotify = data.total;
setTimeout(function() {
load_notifications();
}, 300);
});
};
load_pictures();
load_notifications();
If you only use websockets, you will need to run a query every time to determine if anything has changed. I propose, use a real time DB.
You could use RethinkDB or Firebase with AngularFire. Those are realtime databases and will notify you when there is an update to any of those fields.
If you use RethinkDB, then you will also need to implement a websocket solution to notify the browser.

Web app data storage

Let's say I have two or more tabs with a couple of inputs and textareas.
Users can fill these fields and switch tabs but I want to make sure they don't lose the data in the fields.
Here comes the question: how would you save the data when the users switch between tabs?
Now I solved this problem by storing the data in variables, specifically in object literal (Javascript), but it is such a mechanical way to do it.
Of course I could push the data in a database.
I am using Javascript plus jQuery. I would really like to think of a good way to solve this kind of problem.
You can use localStorage.
Just set the values you want to store by:
localStorage.setItem(key, stringData);
To get the data:
var stringData = localStorage.getItem(key);
To delete:
localStorage.removeItem(key);
That way the data is stored locally in the user's browser. User can also come back later and data will still be there.
You can synchronize the tabs by listening the storage event:
window.addEventListener('storage', updateStorage, false);
function updateStorage(e) {
if (e.newValue === null) {
localStorage.removeItem(e.key);
} else {
localStorage.setItem(e.key, e.newValue);
}
}
The storageevent is only throw to the inactive tabs so they can update the isolated copy of the localStorage.
If you only need to store the data for a session you can use sessionStorage instead.
For more on localStorage:
http://www.w3.org/TR/2013/PR-webstorage-20130409/

Best Method to persist data locally in Windows 8 app

I'm creating a Windows 8 App (using HTML 5 and JavaScript) for someone and they've changed up the requirements on me as far as data storage and I could use some guidance. What I need is a data source that will persist only for the local user and not be online in a database or in the cloud. The users will be assigned a tablet with the app installed and they will enter data via forms to customize their local copy.
Here's my requirements:
-Data MUST persist through the lifetime that the app is installed on the device.
-I need to be able to query the data to some degree. I've basically got about 15-20 forms that will accept input data and then a main form that will feed off those 15-20 "sub" forms to populate drop-down and selection options.
-Size should not be an issue, it's all text data and not much of it will be entered. Can't see this going more than a couple hundred MBs over the lifetime of the app.
I've looked into XML, indexedDB (sounds good on the outside, but haven't found any kind of guarantee this will persist), and Application Data (local) which seems extremely limited in my reading capabilities.
What do you think my best bet is? Any advice would be greatly appreciated.
Thanks.
This should help
(function () {
"use strict";
var page = WinJS.UI.Pages.define("/html/index.html", {
ready: function (element, options) {
//do your things
}
});
var roamingFolder = Windows.Storage.ApplicationData.current.roamingFolder;
var afile = "FileToStoreStuff.txt";
function makefile() {
roamingFolder.createFileAsync(afile, Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (file) {
return Windows.Storage.FileIO.writeTextAsync(file);
})
}
function fileRead() {
roamingFolder.getFileAsync(filename)
.then(function (file) {
return Windows.Storage.FileIO.readTextAsync(file);
}).done(function (text) {
//do stuff
);
}
})();
This kind of assumes that your data may change. If it doesn't you can adapt a different approach, for instance replacing the roamingFolder variable with something like:
var localSettings = applicationData.localSettings;
var localFolder = applicationData.localFolder;
Take a look at the dev docs if you need to access data from within the app elsewhere.

What's the best way use caching data in js on client side?

My application receives data from the another server, using API with limited number of requests. Data changing rarely, but may be necessary even after refresh page.
What's the best solution this problem, using cookie or HTML5
WebStorage?
And may be have other way to solve this task?
As much as cross browser compatibility matters, cookie is the only choice rather than web storage.
But the question really depends on what kind of data you are caching?
For what you are trying, cookie and web-storage might not be needed at all.
Cookies are used to store configuration related information, rather than actual data itself.
Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP request header. [1]
I would rather say, it would be stupid to cache the entire page as cookie or web-storage both. For these purposes, server-side caching options might be the better way.
Update:
Quoting:
data about user activity in some social networks (fb, vk, google+)
Detect the web-storage features, using libraries like mordernizr and if does not exists fall back to cookie method. A simple example
if (Modernizr.localstorage) {
// browser supports local storage
// Use this method
} else {
// browser doesn't support local storage
// Use Cookie Method
}
[1]: http://en.wikipedia.org/wiki/Web_storage
I wrote this lib to solve the same problem:
Cache your data with Javascript using cacheJS
Here are some basic usages
// just add new cache using array as key
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:1,type:'json'}, jsonData);
// remove cache using key
cacheJS.removeByKey({blogId:1,type:'json'});
// add cache with ttl and contextual key
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', 3600, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd'});
// remove cache with con textual key
// cache for blog 2 and 3 will be removed
cacheJS.removeByContext({author:'hoangnd'})
Here is an example of caching data from JQuery AJAX. So if you only want to make the call when you don't have the data yet, its really simple. just do this (example). Here we first check if we have the load information (keyed on line, location and shipdate), and only if we dont, we make the AJAX call and put that data into our cache:
var dict = [];
function checkCachedLoadLine(line, location, shipDate, callback) {
var ret = 0;
if(!((line+location+shipDate) in dict)) {
productionLineService.getProductionLoadLine(line, location, shipDate, callback);
}
return dict[line+location+shipDate];
}
...then in the call back write the value to the cache
function callback(data) {
if (!data) {
document.getElementById('htmlid').innerHTML = 'N/A';
} else {
document.getElementById('htmlid').innerHTML = data[0];
dict[data[2]+data[3]+data[4]] = data[0];
}
}

Categories