Plot 43 Cadestral Zone B, APO, Abuja info@kastechnet.com

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

  • The Evolution of ICT

    kAsTech Network

  • Unleashing the Power of PHP: A Cornerstone in the World of Web Development

    kAsTech Network

  • Embracing Excellence: Kastech Unveils Latest Updates for Managed Applications

    kAsTech Network

  • Latest Balada Injector Campaign Targets Unpatched tagDiv Plugin

    kAsTech Network

  • Kastech Partners with Cloudflare CDN

    kAsTech Network

  • Top Best VPN - Free and Trusted

    kAsTech Network

  • Kastech Hardens all Built Web Applications with HTTP Security Headers

    kAsTech Network

  • All about DDOS attack

    kAsTech Network