I try to store data from user-input in an object in order to be able to store the data in localstorage. My problem is that I cant figure out how to make it work. When I write something as value inside the object (data) it works fine but the user-input cant be stored as value in my object.
Any suggestions?
Thank you for your answers.
You can only store strings in localStorage, so you need some way to convert the object to a string first. JSON.stringify() does this.
var obj = {};
obj.userInputValue = "Pretend a user entered this";
var objAsString = JSON.stringify(obj);
localStorage.setItem("myObject", objAsString);
Related
I have the following code:
localStorage.setItem("ActiveDataOfpModel", iHandle.find("ul li.pModel.active"));
When i check "ActiveDataOfpModel" value in console i get "[object Object]".
How can i store the actual object in "ActiveDataOfpModel" and retrieve its properties. i.e. i want to do the following:
var value = localStorage.getItem("ActiveDataOfpModel").attr("data-id")
i did try
var value = JSON.parse(localStorage.getItem("ActiveDataOfpModel")).attr("data-id")
but its not working
You can only store strings in local storage.
You can encode simple objects as JSON (they must contain only JSON data types such as objects, numbers, and strings) as a string using JSON.stringify(someObject).
var value = JSON.parse(localStorage
… and that is how to convert the JSON back to an object afterwards.
Your code iHandle.find("ul li.pModel.active") implies you are not dealing with a simple object though. That is something I would expect to return a DOM element or something akin to it.
You would need to extract the data you care about from it, store that in an object, store that in the JSON and then the localstorage, and write more code to convert the simple data back in to the full object when you pull the data out afterwards.
Try this:
Convert it to String before saving to LocalStorage
localStorage.setItem('key', JSON.stringify(data));
Convert back to JSON object, when reading from LocalStorage
data = JSON.parse(localStorage.getItem('key');
I am trying to send an information from one page to another through javascript file
the information will only contain a value of single variable.
how to accomplish this?I dont want to send it through query string as the value will be visible in the URL.
is there any other way?
You could save your data in LocalStorage and retrieve it on the other page.
localStorage.yourData = '{ test:"data" }';
console.log(localStorage['yourData']);
You have a few options to do that.
Depending on what browser is used, using localStorage is an option
//localStorage ONLY stores flat key:value pairs and can't contain Objects
localStorage.myString = "hello world";
localStorage.myObject = JSON.stringify({ foo: "bar" });
//Reading back the values is simple aswell
var myString = localStorage.myString;
var myObject = JSON.parse(localStorage.myObject);
Another method would be using a hash or query string. For example, you could redirect to www.yourdomain.com/your/path?myValue=1234
And then parse that by reading the search value from window.location.search (Will return ?myValue=1234 in that case) and splitting it on =:
var myValue = window.location.search.split("=")[1];
Another option is using hashes, similar to query params. Or even cookies.
BUT, all these methods will expose the value to the user, so if he wants to get that value, he will be able to!
At first, as other answers, use localStorage or sessionStorage to store global data.
Otherwise, you can add an event listener to detect the change of the storage value in your target page as follow:
window.addEventListener('storage', (e) => console.log(e.key, e.oldValue, e.newValue))
See: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Responding_to_storage_changes_with_the_StorageEvent
Hello I am doing a form and I used a populate method to fill a form out in jJQuery (Yes I know jquery is just a library) for testing. Now I save the data in the form using Json and Local Storage. Then I call back the object in local storage and use Json to turn it back into a string. The problem is the string will be the EXACT same as the string i hard coded into the populate method but when I put the string to replace it (so its always using current form saved data) it will not work correctly. I'm assuming it is something small.
This is my object called back from local storage and turned back into a string.
var myString = localStorage.getItem("all");
var myStringSave = JSON.stringify(myString); //my string
myStringSave will contain for example:
Name:'Joe',dateBirth:'01/02/1992'
Which is the exact same as my hard coded one. However hardcoded works
$('#frm').populate({Name:'Joe',dateBirth:'01/02/1992'})
But the one in the string will not work:
$('#frm').populate(myStringSave)
or
$('#frm').populate({myStringSave})
I have been looking at it for a few hours and it makes no sense. The string is the exact same as my hard coded one, so why does it not work? Thank you any help is greatly appreciated.
populate accepts a JSON as parameter, and you give it a string.
The basic form for using Populate is: $(selector).populate(JSON,
options)
Don't do :
var myString = localStorage.getItem("all"); // this IS a string (localStorage can't store anything else)
var myStringSave = JSON.stringify(myString); // you stringify a string
You can get your JSON back by using :
myJsonSave = JSON.parse( localStorage.all )
Then $('#frm').populate(myJsonSave) should work.
You can even do it all in one line :
$('#frm').populate( JSON.parse( localStorage.all ) )
This is for a gaming application.
In my game I want to save special effects on a player in a single field of my database. I know I could just put a refrence Id and do another table and I haven't taken that option off the table.
Edit: (added information) This is for my server in node not the browser.
The way I was thinking about storing the data is as a javascript object as follows:
effects={
shieldSpell:0,
breatheWater:0,
featherFall:0,
nightVision:0,
poisonResistance:0,
stunResistance:0,
deathResistance:0,
fearResistance:0,
blindResistance:0,
lightningResistance:0,
fireResistance:0,
iceResistance:0,
windResistance:0}
It seems easy to store it as a string and use it using effects=eval(effectsString)
Is there an easy way to make it a string or do I have to do it like:
effectsString=..."nightVision:"+effects.nightVision.toString+",poisonResistance:"+...
Serialize like that:
JSON.stringify(effects);
Deserialize like that:
JSON.parse(effects);
Use JSON.stringify
That converts a JS object into JSON. You can then easily deserialize it with JSON.parse. Do not use the eval method since that is inviting cross-site scripting
//Make a JSON string out of a JS object
var serializedEffects = JSON.stringify(effects);
//Make a JS object from a JSON string
var deserialized = JSON.parse(serializedEffects);
JSON parse and stringify is what I use for this type of storatge
var storeValue = JSON.stringify(effects); //stringify your value for storage
// "{"shieldSpell":0,"breatheWater":0,"featherFall":0,"nightVision":0,"poisonResistance":0,"stunResistance":0,"deathResistance":0,"fearResistance":0,"blindResistance":0,"lightningResistance":0,"fireResistance":0,"iceResistance":0,"windResistance":0}"
var effects = JSON.parse(storeValue); //parse back from your string
Here was what I've come up with so far just wonering what the downside of this solution is.
effectsString="effects={"
for (i in effects){
effectsString=effectsString+i+":"+effects[i]+","
}
effectsString=effectsString.slice(0,effectsString.length-1);
effectsString=effectsString+"}"
Then to make the object just
eval(effectsString)
Currently, I'm trying to pass a multidimensional array in Phonegap between two pages with window.localStorage. In main.js, I use
var storage = window.localStorage;
storage.setItem("information", myArray);
window.location = "summary.html";
And in the file summary.js, I use:
var storage = window.localStorage;
var myArray = storage.get("information");
When I run this, myArray only returns undefined. I know that it is fully defined right before I call window.location = "summary.html";. My best guess to the problem right now is that there is an error in either storing or retrieving an array, at least the way I'm doing it. Can you not pass Arrays through localStorage, or am I doing something wrong?
I typically use JSON.stringify and JSON.parse when getting or saving items to local storage. I believe most implementations only support strings at the moment.