7 Anthony Udoh Street Ajao Estate, Lagos, Nigeria [email protected]

kAsTech - Read More

Settings Cookies With JQUERY



I've never really used or dealt with browser cookies before because I felt like it was some complicated, advanced technique that required intricate knowledge of how browsers and sessions work.

Today at work, I was given a task that involved setting, checking, and removing cookies for our web application, but I pleasantly found that it was an almost laughably easy task with my best friend JQuery.

DOWNLOAD THE PLUGIN

First, you need to download the handy JQuery cookie plugin here: JQuery Cookie Plugin!

SETTING COOKIES

To set cookies, all you need to do is type in the following in Javascript:

$.cookie("cookieName", "cookieValue");


This default cookie creation links this particular cookie to the session and it will be deleted at the end of some amount of time or if the user closes the browser, etc. If you want to have a cookie stay for a defined amount of time instead of linking it to the session, you can do something like this:
$.cookie("cookieName", "cookieValue", { expires: 1 }); // 1 day


The expiration parameter's unit is in days so if you want to, say, set a cookie for only 30 minutes you'll have to do something a little tricker (I found this cool tip on Stack Overflow):
var date = new Date();
date.setTime(date.getTime() + (30 * 60 * 1000));
$.cookie("example", "foo", { expires: date });


You can also set the path and domain of the cookie (default is the current path and current domain):
$.cookie("cookie", "1", { domain: "domain.com", path: "/" });


READING COOKIES
It's really easy to read back a cookie's value:
$.cookie("cookieName");

Really, that's it!

DELETING COOKIES
Finally, to delete a cookie just set it to null:
$.cookie("cookieName", null);


Note that by default, this plugin won't let you delete a cookie from another domain so you'll have to explicitly specify the domain and path:
$.cookie("cookieName", null, { domain: "domain.com", path:"/");

OTHER BLOG POST

  • Kastech Protects all its Application against XSS

    kAsTech Network

  • Settings Cookies With JQUERY

    kAsTech Network

  • Pros and Cons of Artificial Intelligence - Forbes

    kAsTech Network

  • BlueBorne - The Bluetooth Virus

    kAsTech Network

  • kAsTech Upgrades School Portal

    kAsTech Network

  • KasTech unveils KasHost

    kAsTech Network

  • Kastech Launches Website

    kAsTech Network