11

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:

JSON test

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.

dangerChihuahua007
  • 20,299
  • 35
  • 117
  • 206
  • 2
    I think the issue is that the cookie mechanism is not defined for files on the local disk. Have you tried setting up a local web server and serving your file as `http://localhost/application.html`? – Niklas B. Jan 29 '12 at 19:58
  • Thanks! I ended up just using local storage. It's much more straightforward and works both locally and on a web server. The downside is, of course, older browsers don't support it, which is fine for me. http://coding.smashingmagazine.com/2010/10/11/local-storage-and-how-to-use-it/ – dangerChihuahua007 Jan 30 '12 at 02:08

3 Answers3

11

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.

Dave Watts
  • 890
  • 7
  • 11
  • Thanks, I hosted the site on a public web server, and the cookies worked. This page has more details: http://code.google.com/p/chromium/issues/detail?id=535 – dangerChihuahua007 Jan 29 '12 at 22:05
  • 1
    @DavidFaux looks like you are using Chromium, so I can assume you are also using linux... well if you would like to setup a local webserver for testing you can `sudo apt-get install lamp-server^` then `sudo adduser www-data`, then the following two commands. `sudo chown -R www-data:www-data /var/www` and `sudo chmod -R g+rw /var/www` should just about do it! then all your web dev goes in `/var/www` and you test by navigating to http://localhost/ – rlemon Jan 30 '12 at 02:03
2

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.
rlemon
  • 17,518
  • 14
  • 92
  • 123
  • 1
    Sure this works for web pages on the local disk? AFAIK some browser don't handle local cookies at all. – Niklas B. Jan 29 '12 at 19:59
  • 1
    I have not tested that case.. however if cookies are not available locally, assuming the OP is using a modern browser *local storage* should work out.. – rlemon Jan 30 '12 at 01:59
  • Thanks! Local storage is working brilliantly. It's so simple too. http://coding.smashingmagazine.com/2010/10/11/local-storage-and-how-to-use-it/ – dangerChihuahua007 Jan 30 '12 at 02:06
1

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!

daniel0mullins
  • 1,937
  • 5
  • 21
  • 45
  • Last update of jquery.cookie is 7 days ago, on 2013-09-11. We are using that component that is very useful. – foxontherock Sep 18 '13 at 17:28
  • Could be that they picked up development again. When I made this comment the library hadn't been updated in over 2 years. – daniel0mullins Sep 19 '13 at 15:57
  • As of today, October 28 2015, the project has been totally updated and has a different name and implementation: https://github.com/js-cookie/js-cookie ... The old jquery.cookie script wasn't working for me at all, so I looked into it and switched over to the this new project and it is working well. – Erin Geyer Oct 29 '15 at 03:22