jQuery – Cookies with jquery.cookie

Use of jquery.cookie, a plugin which makes cookie processing simple.

Download jquery.cookie: repository on GitHub. Add jquery.cookie.js  in your page(s). Include it after the jQuery library.

Examples

Tracks the number of times the user has visited a website:

$.cookie("visits", 10);

Stores the user’s favourite city, and specifying the domain and the path where the cookie can be read and written:

$.cookie("favourite-city", "London", {path: "/", domain: "jspro.com"});

Stores the name of the user. This cookie expires on October 29, 2013 at 11 a.m., and can only be sent through a secure connection.

$.cookie("name", "Aurelio", {expires: new Date(2013, 10, 29, 11, 00, 00), secure: true});

Retrieving Cookies

To retriev a cookie is you need to pass the name of the cookie, to retrieve it, as shown by the following examples:

Retrieve the number of times the user has visited the website:

console.debug($.cookie("visits")); // print "10"

Retrieve the name of the user:

console.debug($.cookie("favourite-city")); // print "London" 

Delete a Cookie

Tthe removeCookie() method. Returns true if the requested cookie is found, and false otherwise.

Just pass the options  path and domain,

Removing cookie storing site visits:

$.removeCookie("visits"); // successfully deleted 

To remove the cookie storing the user’s favourite city:

$.removeCookie("favourite-city", {path: "/", domain: "jspro.com"}); // successfully deleted

Next, attempt to remove the cookie storing the user’s name. This example fails because the secure value was not specified.

$.cookie("name"); // fails because the secure value is missing

Usage

Create session cookie:

Create expiring cookie, 7 days from then:

Create expiring cookie, valid across entire site:

Read cookie:

Read all available cookies:

Delete cookie:

Note: when deleting a cookie, you must pass the exact same path, domain and secure options that were used to set the cookie, unless you’re relying on the default options that is.

 

  • SchneiderzZ

    First!