LocalStorage error and idea - javascript

This is my code:
// store item
localStorage.setItem("blog_key", "value I am storing");
// retrieve item
var data = localStorage.getItem("blog_key");
I'm trying to make it list of array for the post, so when somenone click post, it will serve as blog post

Not sure if I got your question or not but I guess you want to do something like this:
// retrieve the local storage value or "[]" and then parse it
var data = JSON.parse(localStorage.getItem("blog_key") || "[]");
// add new item to the array - might want to make sure that the array wont grow too big
data.push("something new");
// store item as string
localStorage.setItem("blog_key", JSON.stringify(data));
I might be wrong though, but that's what I got from your question.

Related

Javascript localstorage get the value into array one by one

Problem:
I would like get the localstorage value "car", i want to get the result like car = ["red","blue"] in other page, i want to get the result into array one by one. How can i fix it?
page 1:
car = ["red","blue"];
localStorage.setItem("car", JSON.stringify(car));
Another Page:
var car1 = JSON.parse(localStorage.getItem("car"));
alert(car1[0])
****show two record at the same time , i want to put it into array like car1[0] = red; car1[1] = blue;
as i know, when you convert it to json it wouldn't parse to you items like array
so car[0] doesn't work as you want,
This is a good resource of using localstorage:
https://www.smashingmagazine.com/2010/10/local-storage-and-how-to-use-it/
U must enter the items as an object and give them an id
like this:
{
name: red,
id: 1,
}
Then retrieve it by car id.
and a better answer: How do I store an array in localStorage?
And know it JSON is not supported in IE7 and earlier.

remember all values in an array using cookies - javascript

i want to be able to remember all values in an array using cookies, but do not know how. I am also using js-cookies.
Here is my code:
var usernames = new Array();
var input = $('#input').val();
usernames.push(input);
// each time something is inputted, it'll be saved to the
// array usernames. I want it so that when refreshed, all
// of the inputs remain in 'usernames'
alert(usernames);
As mentioned, localStorage is a better place to store this data, but using cookies follows the same steps, just need to get a set/get method for Cookies. First you need to see if there is a value. If there is you need to parse it. After you update the array, you need to convert the value to a string and store it.
//Read local storage to see if we have anything saved
var lsUserNames = localStorage.getItem("usernames");
//Get the usernames array
var usernames = lsUserNames ? JSON.parse(lsUserNames) : [];
//Just using prompt to get the username instead of making form
var uname = window.prompt("Enter Name");
if(uname) usernames.push(uname);
//set the updated array to local storage
localStorage.setItem("usernames", JSON.stringify(usernames));
console.log(usernames.join());

dynamic array to local storage/jstorage?

I am pushing values in to my array every 10 seconds which is being displayed by innerHTML on a div.
Onreload or on visit to some other web page I want to display the already pushed content and the content being pushed presently.
I have gone through local stroage and jstorage tutorials.
This is what I am doing precisely=:
localStorage.setItem('names', xyz);
I know how to store one variable,but what when we have a dynamic array being updated/10sec and data being pushed in it every 10 seconds.how do I set and get this dynamic array even when I go to some other link.
If you are interested in my code:http://jsfiddle.net/vCcnB/
UPDATE 1----for simplification(ignore if you have understood.)
This is what is being displayed in my div.Page1 indicates the page and 0,10,20 indicates time.
# 10 seconds----[page1,0]
[page1,10]
#20 seconds-----[page1,0]
[page1,10]
[page1,20]
now a click to some other page.
#10 seconds----[page1,0]
[page1,10]
[page1,20]
[page2,0]
[page2,10]
now a click to some other page.
#20 seconds----[page1,10]
[page1,20]
[page2,0]
[page2,10]
[page3,0]
[page3,10]
[page3,20]
You can use json object for this like,
localStorage.setItem('names', {'ABC','XYZ'}); //and so on
or json string like
var json={'ABC','XYZ'};
localStorage.setItem('names', JSON.stringify(json)); //and so on
To get an existing item try this,
console.log(localStorage.getItem('names'));
Read this https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Storage
You have to JSON.stringify and JSON.parse your array to store and load it respectively.
// initialize
var myArray = [];
// load saved array
if(window.localStorage["savedArray"] != null)
myArray = JSON.parse(window.localStorage["savedArray"]);
// modify array
myArray.push("abc123");
// re-save array
window.localStorage["savedArray"] = JSON.stringify(myArray);

Deserializing JavaScript object instance

I am working on an app that heavily uses JavaScript. I am attempting to include some object-oriented practices. In this attempt, I have created a basic class like such:
function Item() { this.init(); }
Item.prototype = {
init: function () {
this.data = {
id: 0,
name: "",
description: ""
}
},
save: function() {
alert("Saving...");
$.ajax({
url: getUrl(),
type: "POST",
data: JSON.stringify(this.data),
contentType: "application/json"
});
}
}
I am creating Item instances in my app and then saving them to local storage like such:
Item item = new Item();
window.localStorage.setItem("itemKey", JSON.stringify(item));
On another page, or at another time, I am retriving that item from local storage like such:
var item = window.localStorage.getItem("itemKey");
item = JSON.parse(item);
item.save();
Unfortunately, the "save" function does not seem to get reached. In the console window, there is an error that says:
*save_Click
(anonymous function)
onclick*
I have a hunch that the "(anonymous function)" is the console window's way of saying "calling item.save(), but item is an anonymous type, so I am trying to access an anonymous function". My problem is, I'm not sure how to convert "var item" into an Item class instance again. Can someone please show me?
Short answer:
Functions cannot be serialized into JSON.
Explanation:
JSON is a cross-platform serialization scheme based on a subset of JS literal syntax. This being the case, it can only store certain things. Per http://www.json.org/ :
Objects: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
Arrays: An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
values: A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
Functions cannot be serialized into JSON because another non-JS platform would not be able to unserialize and use it. Consider the example in reverse. Say I had a PHP object at my server which contained properties and methods. If I serialized that object with PHP's json_encode() and methods were included in the output, how would my JavaScript ever be able to parse and understand PHP code in the methods, let alone use those methods?
What you are seeing in your resulting JSON is the toString() value of the function on the platform you're using. The JSON serilizer calls toString() on anything being serialized which isn't proper for JSON.
I believe your solution is to stop storing instances in JSON/local storage. Rather, save pertinent data for an instance which you set back to a new instance when you need.
I know this question is answered already, however I stumbled upon this by accident and wanted to share a solution to this problem, if anyone is interested.
instead of doing this:
var item = window.localStorage.getItem("itemKey");
item = JSON.parse(item);
item.save();
do something like this:
// get serialized JSON
var itemData = window.localStorage.getItem("itemKey");
//instantiate new Item object
var item = new Item();
// extend item with data
$.extend(item, JSON.parse(itemData));
// this should now work
item.save();
this will work so long as the function you are wanting to call (ie, save()) is prototypal and not an instance method (often times the case, and is indeed the case in the OP's original question.
the $.extend method is a utility method of jquery, but it is trivial to roll your own.
You cant do that, how can javascript possibly knows that item have a save function ? json doesnt allow functions as datas. just read the json spec , you cant save functions.
what you need to do is to create a serialize and deserialize method in the hash you want to stock. that will specifiy what to export and how you can "wake up" an object after parsing the corresponding json string.
You can only store plain Objects in DOMstorages (cookies, urlparams..., everything that needs [de]serialisation through JSON.stringify/JSON.parse). So what you did when sending the ajax data
ajaxsend(this.data);
also applies to string serialisation. You can only store the data, not the instance attributes (like prototype, constructor etc.). So use
savestring(JSON.stringify(item.data));
which is possible because item.data is such a plain Object. And when restoring it, you will only get that plain data Object back. In your case it's easy to reconstruct a Item instance from plain data, because your Items hold their values (only) in a public available property:
var item = new Item;
item.data = JSON.parse(getjsonstring());
Disclaimer
Not a full time time J.S. Developer, answer may have some minor bugs:
Long Boring Explanation
As mentioned by #JAAulde, your object cannot be serialized into JSON, because has functions, the technique that you are using doesn't allow it.
Many people forget or ignore that the objects that are used in an application, may not be exactly the same as saved / restored from storage.
Short & quick Answer
Since you already encapsulate the data members of your object into a single field,
you may want to try something like this:
// create J.S. object from prototype
Item item = new Item();
// assign values as you app. logic requires
item.data.name = "John Doe";
item.data.description = "Cool developer, office ladies, love him";
// encoded item into a JSON style string, not stored yet
var encodedItem = JSON.stringify(item.data)
// store string as a JSON string
window.localStorage.setItem("itemKey", encodedItem);
// do several stuff
// recover item from storage as JSON encoded string
var encodedItem = window.localStorage.getItem("itemKey");
// transform into J.S. object
item.data = JSON.parse(encodedItem);
// do other stuff
Cheers.

How to store temporary data at the client-side and then send it to the server

I need to store data temporarily at the client-side to allow users to add, edit or delete items without having to query the server for each of these actions; just when the user finishes adding items and clicks on the Add button, the list is sent to the server to be saved permanently.
This image describes what I want to achieve.
I know I have to use arrays in JavaScript, but I don't know how to create one to store objects (in this case Detail which contains :id, price and description).
I hope you can help me out.
Thanks in advance.
PS: I'm using JSP and... sorry for my English
Sure, since it's a table it makes sense to have an array of objects. Note that an object is surrounded by curly braces and an array is surrounded by brackets:
var myArray = []; // Initialize empty array
var myObject = {}; // Initialize empty object
This should accomplish what you need:
// Initialize variables
var newEntry, table = [];
// Create a new object
newEntry = {
id: '',
price: '',
description: ''
};
// Add the object to the end of the array
table.push(newEntry);
Which is the same as this:
// Initialize array
var table = [];
// Create object and add the object to the end of the array
table.push({
id: '22',
price: '$222',
description: 'Foo'
});
You can now access properties like this:
table[0].id; // '22'
On modern browsers, if you want the data to persist across sessions (like cookies) you could use the sessionStorage or localStorage objects.
When you want to send the data to the server, you'll send a JSON version of the table across the wire:
var data = JSON.stringify(table);
You can create an Array of your custom Detail objects pretty easily with object literals:
var details = [];
details.push({id:'abc1234', price:999.99, description:'Tesla Roadster'});
details.push({id:'xyz5678', price:129.99, description:'Land Rover'});
Then you can post your data to the server when the user clicks "Add."
Sounds like a good job for JSON.

Categories

Resources