I am attempting to create a cookie. I suspect that my cookie isnt saving or being retrieved properly. What am I doing wrong?
I tried 2 methods to save this cookie:
Cookie gets saved in this function:
function(config) {
var config_copy = JSON.parse(JSON.stringify(config));
setCookie('key',config_copy);
}
Use setCookie();
function(config) {
var config_copy = JSON.parse(JSON.stringify(config));
setCookie();
}
Then trigger this function:
function setCookie(key,config_copy){
document.cookie = key + "=" + config_copy;
console.log("cookie saved");
console.log(config_copy);
}
console.log(config_copy); returns undefined in the console.
How would I correctly save the value of config_copy into a JavaScript cookie?
JSON.parse() returns an object, not a JSON string. You should put the JSON string into the cookie, not the result of JSON.parse.
function saveConfig(config) {
var config_copy = JSON.stringify(config);
setCookie("key", config_copy);
}
Otherwise, you'll just set the cookie to [Object object].
Document.cookie only accepts primitive values, if you pass an object it calls Object.toString() which returns [ object Object ].
You have too options for storing an object in cookie form.
Multiple cookies from an object's properties
If you want to make a cookie out of each property of an object, you have to loop through the object and create a cookie out of each property.
var saveConfig = function(config) {
var cookies = [];
for(var i in config)
cookies.push(document.cookie = i + '=' + config[i]);
return cookies;
}
saveConfig({hello: 'world', foo: 'bar'});
console.log(document.cookie);
Outputs: hello=world; foo=bar;
One cookie from an object converted to a string
You can convert the object to a string and store it in one cookie using JSON.stringify().
var saveConfig = function(config) {
return document.cookie = 'config=' + JSON.stringify(config);
}
saveConfig({hello: 'world', foo: 'bar'});
console.log(document.cookie);
Outputs: config={"hello":"world","foo":"bar"};
In your second "option" you have to send a value for the parameters like this:
function(config) {
var config_copy = JSON.parse(JSON.stringify(config));
setCookie("key", config_copy);
}
if you call it without the parameters, they will have an undefined value
You need to pass your variables to setCookie() in order for the function to use them.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Calling_functions
Related
I am unable to access a simple JSON Element from a JSON Structure that looks like:
{
"ACTION": "AA",
"MESSAGE": "Customer: 30xxx Already Approved on 2017/01/01"
}
I get the data in JSON Format but when i do data.ACTION or data.MESSAGE i get Undefined as the output.
By doing case sensitive also, its not working( Image attached )
var url = base + query;
var getJSON = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.withCredentials = true;
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON(url).then(function (data) {
console.log(data); //Getting JSON Data
var output = JSON.stringify(data);
var obj = JSON.parse(output.replace(/ 0+(?![\. }])/g, ' '));
console.log(output);
console.log(obj.message); //Here getting UNDEFINED
}, function (status) { //error detection....
alert('Something went wrong.');
});
Console:
{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}
stringify returns the following
{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}"
EDITED. I first thought the error was due to parsing, given the print. -.-
Solution:
When you print the output, obj it's still a string, not an object. So it is OK at that point.
Your "undefined" property message should be replaced by MESSAGE.
Instead of console.log(obj.message); just use console.log(obj.MESSAGE);
Also. An example of parsing JSON:
var myJson = '{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}';
console.log(myJson); // This prints the literal string
console.log(JSON.parse(myJson)); // this prints an "object"
obj.message property is not defined and when you try to get the property which is not defined on an object, you get undefined.
Javascript is case sensitive. You should try obj.MESSAGE instead to get the property value. Also, to check if a property exists on an object you can make use of object.hasOwnProperty([propName]) method to check if a property exists on a object or not.
EDIT 1: Try running the following code snippet. JSON data string is parsed before accessing the property.
var jsonString = "{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}";
var obj = JSON.parse(jsonString);
console.log(obj.MESSAGE);
data already is a JSON string, there's no need to JSON.stringify it (which returns a string with a JSON-encoded string literal). Parsing it into output only leads to a string again, which has no properties. You should use
console.log(data);
var obj = JSON.parse(data);
console.log(obj);
obj.MESSAGE = obj.MESSAGE.replace(/ 0+(?![\. }])/g, ' ');
(notice the proper casing of the property name)
You can try:
var jsonObject = data.data;
console.log(jsonObject.ACTION)
This has been asked a bunch of times before but I'm not grasping it.
In the following..
var variableName = "hello";
How do I make the variable name 'variableName' based on another variable?
PHP Example
$a = 'hello';
$$a = 'hi'; // same as $hello..
echo $hello; // and $hello outputs 'hi'
I specifically need this variable variable to be used for localstorage so it may be syntax that I'm having a problem with.
What I'm Using It For (you can probbaly skip to This Seems To Work)
I want to generate a unique variable name for storing information in local storage. Variable name will be based on the post id of the wordpress post/page which I retrieve with php.
For example we will say the post id is 3333
I add the letters id to the beginning of each post id
So now I have id3333
var postIdNumber = 'id3333';
Then I get 3 other pieces of information that I want to store into local storage about this post (for simplicity I have shown an example output, not the code to get it)
var postURL = 'website.comm/a-wp-post/';
var postTitle = 'A Wordpress Post';
var postThumb = 'website.comm/images/thumb3333.jpg';
Now I want to store this information into local storage
var lsTest = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('lsTest', JSON.stringify(lsTest));
That works fine. Except that I want to be able to store multiple posts into local storage to retrieve later from a 'my favourite posts' page.
So I need a dynamic variable name.
For post ID 3333 I need the variable currently named lsTest to be named id3333
For post ID 4444 I need the variable currently named lsTest to be named id4444
This seems to work (Though I dont fully comprehend it)
solution modified from https://stackoverflow.com/a/5187652/3377049
var variableVariable = {}
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
jQuery('.test-div').text(variableVariable[vv]); // outputs id3333
While this does not..
var variableVariable = {} // also, should this have a ';' ?
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
var variableVariable[vv] = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('variableVariable[vv]', JSON.stringify(variableVariable[vv]));
In PHP I could maybe do something like this.. (for examples sake i'm mixing php variables into JS)
$uv = 'id3333';
$$uv = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('$$uv', JSON.stringify($$uv));
You just need to create an object of objects, keyed off of the unique post id. But then you need to stringify the object before storing it, and parse it when retrieving it.
function saveObject(key, object) {
object = JSON.stringify(object);
window.localStorage.setItem(key, object);
}
function getSavedObject(key) {
var saved = window.localStorage.getItem(key);
if (saved) {
return JSON.parse(saved);
} else {
return null;
}
}
your object:
var lsTest = {
id3333: {
postUrl: postUrl1,
postTitle: postTitle1,
postThumb: postThumb1,
},
id4444: {
postUrl: postUrl2,
postTitle: postTitle2,
postThumb: postThumb2,
}
}
store it:
saveObject('myUniqueSiteName', lsTest);
retrieve it:
var lsTest = getSavedObject('myUniqueSiteName');
adding a new post:
var lsTest = getSavedObject('myUniqueSiteName');
var postId = 'id555';
lsTest[postId] = {
postUrl: postUrl3,
postTitle: postTitle3,
postThumb: postThumb3,
}
saveObject('myUniqueSiteName', lsTest);
Variable variables are not a good idea even in PHP. Just make an array or a hash (which is an object, but it's used as a hash or map, where you can add and delete properties or entries as you please).
var posts = {};
var someId = 3333; //or '3333' if it isn't a number
posts[someId] = {
URL: postURL,
title: postTitle,
thumb: postThumb
};
localStorage.setItem('post' + someId, JSON.stringify(posts[someId]));
A property named "foo" on an object named "bar" can be accessed like so:
bar.foo = 'baz';
console.log(bar.foo);
or like so:
bar['foo'] = 'baz';
console.log(bar['foo']);
Which is the same as:
var name = 'foo';
bar[name] = 'baz';
console.log(bar[name]);
Finally, the global object in JavaScript (which in the browser is window) "holds" the global variables.
var myGlobal = 10;
console.log(window.myGlobal); // logs 10
var globalName = 'foo';
window[globalName] = 'baz';
console.log(foo); //logs 'baz'
Using global variables in general is discouraged. Using them to store posts where the name of the var is the id is highly unorthodox and many JS developers would consider it simply wrong.
Is it possible to use a non static variable with chrome.storage.local.get. Right now, I can not recover anything.
here's what I do:
myVar = 'test';
var obj = {};
obj[myVar] = Output;
storage.set(obj);
and to recover, I do:
var key = example + 'js';
storage.get(key, function (result) {
console.log (result.key)
});
Thank you in advance for your help!
You can pass null as the query to retrieve the whole storage:
chrome.storage.local.get(null, function(data) {
// data contains everything in storage
});
No jQuery.
I want to store an object or array in a cookie.
The object should be usable after page refresh.
How do I do that with pure JavaScript? I read many posts, but do not know how to serialize appropriately.
EDIT:
Code:
var instances = {};
...
instances[strInstanceId] = { container: oContainer };
...
instances[strInstanceId].plugin = oPlugin;
...
JSON.stringify(instances);
// throws error 'TypeError: Converting circular structure to JSON'
How do I serialize instances?
How do I maintain functionality, but change structure of instance to be able to serialize with stringify?
Try that one to write
function bake_cookie(name, value) {
var cookie = [name, '=', JSON.stringify(value), '; domain=.', window.location.host.toString(), '; path=/;'].join('');
document.cookie = cookie;
}
To read it take:
function read_cookie(name) {
var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
result && (result = JSON.parse(result[1]));
return result;
}
To delete it take:
function delete_cookie(name) {
document.cookie = [name, '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.', window.location.host.toString()].join('');
}
To serialize complex objects / instances, why not write a data dump function in your instance:
function userConstructor(name, street, city) {
// ... your code
this.dumpData = function() {
return {
'userConstructorUser': {
name: this.name,
street: this.street,
city: this.city
}
}
}
Then you dump the data, stringify it, write it to the cookie, and next time you want to use it just go:
var mydata = JSON.parse(read_cookie('myinstances'));
new userConstructor(mydata.name, mydata.street, mydata.city);
Use either object's own .toString() method if it gives meaningful serialization or JSON.stringify(). Do note, however, that cookies are usually limited in length and won't be able to hold big amounts of data.
A cookie adaptation class from :
http://www.sitepoint.com/cookieless-javascript-session-variables/
All you need to do is to set and get variables you need to store in cookie.
Work with: int, string, array, list, Complex object
Exemple:
var toStore = Session.get('toStore');
if (toStore == undefined)
toStore = ['var','var','var','var'];
else
console.log('Restored from cookies'+toStore);
Session.set('toStore', toStore);
Class:
// Cross reload saving
if (JSON && JSON.stringify && JSON.parse) var Session = Session || (function() {
// session store
var store = load();
function load()
{
var name = "store";
var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
if (result)
return JSON.parse(result[1]);
return {};
}
function Save() {
var date = new Date();
date.setHours(23,59,59,999);
var expires = "expires=" + date.toGMTString();
document.cookie = "store="+JSON.stringify(store)+"; "+expires;
};
// page unload event
if (window.addEventListener) window.addEventListener("unload", Save, false);
else if (window.attachEvent) window.attachEvent("onunload", Save);
else window.onunload = Save;
// public methods
return {
// set a session variable
set: function(name, value) {
store[name] = value;
},
// get a session value
get: function(name) {
return (store[name] ? store[name] : undefined);
},
// clear session
clear: function() { store = {}; }
};
})();
If you can serialize your object into its canonical string representation, and can unserialize it back into its object form from said string representation, then yes you can put it into a cookie.
I have a javascript Array which I am stringifying in order to store it in localstorage
console.log(request.keywords.length);
localStorage.keywords = JSON.stringify(request.keywords);
where keywords is javascript array. Here request.keywords.length returns 12 which is number of elements in array.
After retrieving it and parsing it back to JSON
var keywords = chrome.extension.getBackgroundPage().getItem("keywords");
var kjos=JSON.parse(keywords);
console.log(kjos.length);
The length returned is 342 which is the length of whole string. I tried getting type of object via constructor.name property, it gives me string instead of Array.
Any ideas what is going wrong ?
Snippets:
Background.html
function getItem(key) {
var value;
log('Get Item:' + key);
try {
value = window.localStorage.getItem(key);
}catch(e) {
log("Error inside getItem() for key:" + key);
log(e);
value = "null";
}
log("Returning value: " + value);
return value;
}
/////
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
localStorage.keywords = JSON.stringify(request.keywords);
}
);
////////////
Popup.js
var keywords = chrome.extension.getBackgroundPage().getItem("keywords");
var kjos=JSON.parse(keywords); //kjos is a string variable
/////
keywords.js
//keywordsArray is an Array object
// Message passing to background page
chrome.extension.sendRequest({message: "setKeywords", keywords: keywordsArray}, function()
{
console.log(keywordsArray);
console.log("message sent");
// The data has been sent, we can close the window now.
//window.close();
});
You need to use request like this - chrome.extension.sendRequest({message: "setKeywords"..., but for getKeywords operation. Function getItem can not be used for access to a variable of background page.