Why does jQuery cookie not actually set a cookie? - javascript

I am developing an application using jQuery that uses cookies. Right now, it is located at application.html on my PC desktop.
However, I cannot store and retrieve a cookie. I had included jquery-1.7.1.min.js, json2.js, and jquery.cookie.js in my HTML file in that order.
Here is how I am storing a cookie to last for 7 days:
$.cookie("people", JSON.stringify(people_obj_array), {expires: 7});
The global array people_obj_array looks like
[
{
"name": "Adam",
"age": 1,
},
{
"name": "Bob",
"age": 2,
},
{
"name": "Cathy",
"age": 3,
},
]
When I test JSON encryption with alert(JSON.stringify(people_obj_array)), it looks fine:
However, when I retrieve this cookie via:
alert($.cookie("people"));
before even refreshing the page, an alert pops up that reads "null." Shouldn't the text be the alert JSON string? Am I using the JQuery cookies library correctly?
Just to clarify, here is how I am testing:
$.cookie("people", JSON.stringify(people_obj_array), {expires: 7}); // store
alert($.cookie("people")); // attempt to retrieve
I have Firebug, and I am willing to do some Console tests.

It's probably the fact the file is on your desktop that's causing the problem. Browsers normally behave by serving up cookies based on the domain they were received from and their path.
You may not be able to read the cookie immediately after setting it: Writing a cookie involves setting headers in a HTTP request and, likewise, reading them involves reading headers in a HTTP response.
Try hosting your page on a web-server and see if that works for you.

If you are having troubles with the cookies plugin why not just make up your own cookie functions? Read, Write and (optional) delete.
var createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = '; expires=' + date.toGMTString();
}
else var expires = '';
document.cookie = name + '=' + value + expires + '; path=/';
};
var readCookie = function(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
};
var eraseCookie = function(name) {
createCookie(name, '', -1);
};
I cannot comment on the specific plugin as I have never used it.. however these functions all work and have been tested.
So for your example:
createCookie("people", JSON.stringify(people_obj_array), 7); // store
alert(readCookie("people")); // retrieve
eraseCookie("people"); // remove
alert(readCookie("people")); // oo look i'm no longer here.

From my research jquery.cookie.js is fairly old, and doesn't seem to be maintained any longer. You might have better luck using this library instead. Its description on Google Code is "Javascript Cookie Library with jQuery bindings and JSON support", and includes methods for everything you're trying to do!

Related

HTML cookie don't create

I'm having problem of creating a cookie, I have this code:
window.onload = function() {
var value = readCookie('username');
if(value == null){
alert("null");
document.cookie = "username=Bob; expires=Thu, 18 Dec 2016 12:00:00 UTC";
}
else
alert(value);
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
When the page load I check if the cookie exists, if it doesn't, I pop up an alert saying that is null, then I create the cookie, but every time I load the page it always says its null. Now the problem is in the creation of the cookie or in the readCookie function. I can't find why this doesn't work.
UPDATE
So in google Chrome it won't work, but in internet explorer works perfectly, someone knows why? I would like to work in all browsers.
When I create an HTML page using that code and run it in a normal test environment, the problem you describe does not occur. It alerts null on the first load and Bob on the second load.
If, however, I tell the browser to load the page from file:///Users/david/tmp/jgfklgjkl/index.html instead of my test server at http://localhost:7007/, then it always alerts null.
Cookies are associated with a hostname, and you have to load the page over HTTP in order to use them.
You are presumably loading them from a local file, and that is where the problem lies, not with your code.
Try this function for reading cookie. I've been using it for quite too long and it's working fine so far
function getCookieValue(cookie_name) {
var cookie, cookies = document.cookie.split(';');
for (var i = cookies.length - 1; i >= 0; --i) {
cookie = cookies[i].split('=');
if (cookie[0].trim() === cookie_name)
return cookie[1];
}
return "";
}
Also if you are interested you could use this function for adding cookies for 10 years.
function addCookie(name, value) {
var expire = new Date();
expire.setFullYear(expire.getFullYear() + 10);
d.cookie = name + "=" + value + "; expires=" + expire.toGMTString() + "; path=/";
}

Set a Javascript Cookie based on URL Params

I'm curious if someone can help a very new Javascript user make sense of how to set a cookie, based on specific URL parameters. I see that pulling the data from the URL using JavaScript is covered in this post:
How can I get query string values in JavaScript?
But I can not figure out how to pull that information into a cookie to store the information throughout a users session on the site.
I would like to grab 3 main URL parameters:
utm_source
utm_medium
utm_campaign
And then store them in a cookie in Google Tag Manager using Javascript.
I can not wrap my head around making this happen. Any help would be greatly appreciated. Sorry I dont have much code to show for reference, but I have been experimenting ( and failing ) for hours now.
Thank you so much for any insight on this.
Cheer,
Melissa
Edit:
Sorry...I wasn't expecting someone to write it for me, I just didn't think my very failed attempts would help anyone see what I was trying to do so I just explained.
Here is my code as of now, and I know it's sort of working. I'm editing a previous cookie that stores the site referrer in a cookie. So as it stands right now, the cookie stores the referrer on the first pageview, then if you go to a different page it will show the {{utm_medium}} and continue to show that throughout the visit. I would like for it to not show the referrer, but output a cookie that displays {{utm_source}} | {{utm_medium}} | {{utm_campaign}} if that's even possible...
Thank you again for any help or pointers or articles. I really appreciate it.
<script> //get referrer info and shorten it
var ref = {{Referrer}}
function extractDomain(url) {
var domain;
//find & remove protocol (http, ftp, etc.) and get domain
if (url.indexOf("://") > -1) {
domain = url.split('/')[2];
} else {
domain = url.split('/')[0];
}
//find & remove port number
domain = domain.split(':')[0];
return domain;
}
ref = extractDomain(ref);
//create cookie
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
var cookie = "";
//check if UTMs are present and set cookie content to the source utm
if ({{utm_source}}) {
createCookie("utmsource", cookie + {{utm_source}}, 1000)
} else if ({{utm_medium}}) {
createCookie("utmsource", cookie + "Email", 1000)
//check if referrer is present and set cookie content to the referrer
} else if ({{utm_campaign}}) {
createCookie("utmsource", cookie + "{{utm_campaign}}", 1000)
} else if {
createCookie("utmsource", cookie + "Email", 1000)
};
</script>
When you use cookie + something, you're not updating the cookie string. So each time you do this, you're just concatenating with the original, empty value of this string. Instead of calling setcookie multiple times, update the cookie string as you test the different variables, then call setcookie at the end with the combined value.
You shouldn't use else if between each test, since that will only add the second variable to the cookie if the first variable didn't exist. But you want all the variables put into the cookie.
var cookie = "";
if ({{utm_source}}) {
cookie += {{utm_source}};
}
if ({{utm_medium}}) {
cookie += ' | ' + {{utm_medium}};
} else {
cookie += ' | Email';
}
if ({{utm_campaign}}) {
cookie += ' | ' + {{utm_campaign}};
} else {
cookie += ' | Email';
}
setcookie('utm_source', cookie, 1000);

Client-side JS session library

I'm looking for a client-side JS library to store session variables.
I'd like a library that supports alternative storage medium, e.g. cookies when available with fallback on other techniques.
For instance, I found this one (but the last update is in 2009):
http://code.google.com/p/sessionstorage/
I'm not interested in security (apart a bit of data isolation among applications), as I'm not going to store sensitive data.
To give an example of use case, I want to display a message "Chrome user? Download the app" for chrome users, and I'd like to maintain a status in session to avoid displaying the message again to the same user. I don't want server-side sessions as I have caching enabled, so I must be able to serve the exact same page to different users.
You can use localStorage if available, and if it's not, then using cookies (or whatever you feel to):
var appToken = createToken();
try {
if (localStorage.getItem) {
localStorage.downloadAppAlert = appToken;
} else {
setCookie('downloadAppAlert', appToken, 10); // name, a string value, num. of days
}
} catch(e) {
console.log(e);
}
Then you can use some function to set your cookies - i.e. this one i just found in w3schools:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
To retrieve a cookie value by it's name - downloadAppAlert in the example - you can use the one on the w3schools link or something like this:
function readCookie(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
Also, to retrieve a previously setted item on the localStorage you simply:
var appToken = localStorage.getItem('downloadAppAlert');
EDIT: Sorry, with the hurries i forgot to mention what createToken() does. It is supposed to be a random alphanumeric generator function. You can find plenty on SO, like:
Random alpha-numeric string in JavaScript?
Generate random string/characters in JavaScript
Generating (pseudo)random alpha-numeric strings
Use node-client-sessions (https://github.com/mozilla/node-client-sessions) by mozilla.

How to write value in text file using Javascript

I'm working on a number of views per page using JavaScript.
<SCRIPT LANGUAGE="JavaScript">
<!--
var cookiec = document.cookie
if (cookiec != "") {
var eqchr = 0;
for (var cloop = 1; cloop <= cookiec.length; cloop++) {
if (cookiec.charAt(cloop) == "=") {
eqchr=(++cloop);
}
}
var cookiess = 0;
clength=cookiec.length;
cookies="";
for (cloop = eqchr; cloop < clength; cloop++) {
if (cookiec==";") {
cloop=clength;
}
else {
cookies = cookies + cookiec.charAt(cloop);
}
}
cookiess = parseInt(cookies);
document.write("[" + cookiess + "]");
cookiess++;
cookies = cookiess;
var one_week = 7 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime(expDate.getTime() + one_week);
document.cookie = "Counter=" + escape(cookies) + "; expires=" + expDate.toGMTString();
}
else {
var one_week = 7 * 24 * 60 * 60 * 1000;
var expDate = new Date();
expDate.setTime(expDate.getTime() + one_week);
document.cookie = "Counter=2; expires=" + expDate.toGMTString();
document.write("[1]");
}
// -->
</SCRIPT>
I am using the above JavaScript to calculate the number of views per page and I want to write the data in a text file.
Do you have any suggestions?
If your JavaScript is running in a browser environment, I would highly recommend either using HTML5 localStorage for storing (key, value) pairs or using AJAX to communicate with a server instead of trying to access a file on the client machine which may potentially become a security/privacy issue. Below is a simple example of using localStorage to store a page view count:
if (localStorage.numberOfViews) {
localStorage.numberOfViews = Number(localStorage.numberOfViews) + 1;
} else {
localStorage.numberOfViews = 1;
}
Hope this helps!
Javascript, running in a normal web browser, has very very limited access to the local file system.
So modern web browsers will let you save data to a file in a specialized directory, isolated from everything else.
For the most part, using localStorage (as mentioned by the others), is your best bet.
If you are running under Windows you can create a specialized file called an '.HTA' which runs with the same kind of access and permissions that regular files use.
Attribute LANGUAGE="JavaScript" is deprecated. You can remove it.
Now, replying your question, you can do it with PHP. Send the data when the user enter the page, send it via AJAX to your server and proccess it with PHP.

HTML5 Local Storage fallback solutions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I'm looking for javascript libraries and code that can simulate localStorage on browsers that do not have native support.
Basically, I'd like to code my site using localStorage to store data and know that it will still work on browsers that don't natively support it. This would mean a library would detect if window.localStorage exists and use it if it does. If it doesn't exist, then it would create some sort of fallback method of local storage, by creating its own implementation in the window.localStorage namespace.
So far, I've found these solutions:
Simple sessionStorage implementation.
An implementation that uses cookies (not thrilled with this idea).
Dojo's dojox.storage, but it is it's own thing, not really a fallback.
I understand that Flash and Silverlight can be used for local storage as well, but haven't found anything on using them as a fallback for standard HTML5 localStorage. Perhaps Google Gears has this capability too?
Please share any related libraries, resources, or code snippets that you've found! I'd be especially interested in pure javascript or jquery-based solutions, but am guessing that is unlikely.
Pure JS based simple localStorage polyfill:
Demo: http://jsfiddle.net/aamir/S4X35/
HTML:
set key: foo, with value: bar<br/>
get key: foo<br/>
delete key: foo​
JS:
window.store = {
localStoreSupport: function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
},
set: function(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else {
var expires = "";
}
if( this.localStoreSupport() ) {
localStorage.setItem(name, value);
}
else {
document.cookie = name+"="+value+expires+"; path=/";
}
},
get: function(name) {
if( this.localStoreSupport() ) {
var ret = localStorage.getItem(name);
//console.log(typeof ret);
switch (ret) {
case 'true':
return true;
case 'false':
return false;
default:
return ret;
}
}
else {
// cookie fallback
/*
* after adding a cookie like
* >> document.cookie = "bar=test; expires=Thu, 14 Jun 2018 13:05:38 GMT; path=/"
* the value of document.cookie may look like
* >> "foo=value; bar=test"
*/
var nameEQ = name + "="; // what we are looking for
var ca = document.cookie.split(';'); // split into separate cookies
for(var i=0;i < ca.length;i++) {
var c = ca[i]; // the current cookie
while (c.charAt(0)==' ') c = c.substring(1,c.length); // remove leading spaces
if (c.indexOf(nameEQ) == 0) { // if it is the searched cookie
var ret = c.substring(nameEQ.length,c.length);
// making "true" and "false" a boolean again.
switch (ret) {
case 'true':
return true;
case 'false':
return false;
default:
return ret;
}
}
}
return null; // no cookie found
}
},
del: function(name) {
if( this.localStoreSupport() ) {
localStorage.removeItem(name);
}
else {
this.set(name,"",-1);
}
}
}​
I use PersistJS (github repository), which handles client-side storage seamlessly and transparently to your code. You use a single API and get support for the following backends:
flash: Flash 8 persistent storage.
gears: Google Gears-based persistent storage.
localstorage: HTML5 draft storage.
whatwg_db: HTML5 draft database storage.
globalstorage: HTML5 draft storage (old spec).
ie: Internet Explorer userdata behaviors.
cookie: Cookie-based persistent storage.
Any of those can be disabled—if, for example, you don't want to use cookies. With this library, you'll get native client-side storage support in IE 5.5+, Firefox 2.0+, Safari 3.1+, and Chrome; and plugin-assisted support if the browser has Flash or Gears. If you enable cookies, it will work in everything (but will be limited to 4 kB).
have you seen the polyfill page on the Modernizr wiki?
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
look for the webstorage section on that page and you will see 10 potential solutions (as of July 2011).
good luck!
Mark
Below is a tidied up version of Aamir Afridi's response that keeps all its code encapsulated within the local scope.
I've removed references that create a global ret variable and also removed the parsing of stored "true" and "false" strings into boolean values within the BrowserStorage.get() method, which could cause issues if one is trying to in fact store the strings "true" or "false".
Since the local storage API only supports string values, one could still store/retrieve JavaScript variable data along with their appropriate data types by encoding said data into a JSON string, which can then be decoded using a JSON encode/decode library such as https://github.com/douglascrockford/JSON-js
var BrowserStorage = (function() {
/**
* Whether the current browser supports local storage as a way of storing data
* #var {Boolean}
*/
var _hasLocalStorageSupport = (function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
})();
/**
* #param {String} name The name of the property to read from this document's cookies
* #return {?String} The specified cookie property's value (or null if it has not been set)
*/
var _readCookie = function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
};
/**
* #param {String} name The name of the property to set by writing to a cookie
* #param {String} value The value to use when setting the specified property
* #param {int} [days] The number of days until the storage of this item expires
*/
var _writeCookie = function(name, value, days) {
var expiration = (function() {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
return "; expires=" + date.toGMTString();
}
else {
return "";
}
})();
document.cookie = name + "=" + value + expiration + "; path=/";
};
return {
/**
* #param {String} name The name of the property to set
* #param {String} value The value to use when setting the specified property
* #param {int} [days] The number of days until the storage of this item expires (if storage of the provided item must fallback to using cookies)
*/
set: function(name, value, days) {
_hasLocalStorageSupport
? localStorage.setItem(name, value)
: _writeCookie(name, value, days);
},
/**
* #param {String} name The name of the value to retrieve
* #return {?String} The value of the
*/
get: function(name) {
return _hasLocalStorageSupport
? localStorage.getItem(name)
: _readCookie(name);
},
/**
* #param {String} name The name of the value to delete/remove from storage
*/
remove: function(name) {
_hasLocalStorageSupport
? localStorage.removeItem(name)
: this.set(name, "", -1);
}
};
})();
I personally prefer amplify.js. It has worked really well for me in the past and I recommended it for all local storage needs.
supports IE 5+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ and provides a consistent API to handle storage cross-browser
store.js uses userData and IE and localStorage on other browsers.
It does not try to do anything too complex
No cookies, no flash, no jQuery needed.
Clean API.
5 kb compressed
https://github.com/marcuswestin/store.js
The MDN page for DOM storage gives several workarounds that use cookies.
Lawnchair seems to be a good alternative too
a lawnchair is sorta like a couch except smaller and outside. perfect
for html5 mobile apps that need a lightweight, adaptive, simple and
elegant persistence solution.
collections. a lawnchair instance is really just an array of objects.
adaptive persistence. the underlying store is abstracted behind a consistent interface.
pluggable collection behavior. sometimes we need collection helpers but not always.
There is realstorage, which uses Gears as a fallback.

Categories