enavu webdevmania tutsvalley psdestination
visit the enavu network
5 Comments Article Title Overlay

Working with cookies using jQuery and JavaScript

Overview on using cookies via jQuery or JavaScript.

Today i want to go over a few techniques to easily use cookies via jQuery (much easier) or pure javascript.
What is a cookie?
A cookie is a text string that is included with Hypertext Transfer Protocol (HTTP) requests and responses. Cookies are used to maintain state information as you [...]

DZoneDiggDesign FloatDeliciousBlinklistRedditFacebookGoogle BuzzTwitterStumbleUponTumblrShare

Overview on using cookies via jQuery or JavaScript.

Today i want to go over a few techniques to easily use cookies via jQuery (much easier) or pure javascript.

What is a cookie?

A cookie is a text string that is included with Hypertext Transfer Protocol (HTTP) requests and responses. Cookies are used to maintain state information as you navigate different pages on a Web site or return to the Web site at a later time. This article provides information about cookies.

What do i do with cookies

Cookies today can be seen used most often for storing user logged in information. That means that with cookies we can allow for our members to set a certain amount of time for their account to stay logged in. Also you use cookies to store very basic temporary information that the website collected from you at one point of time.

Cookies should NOT be used to store information that needs to be accessible by the user or by your website from a variety of places. By places i am referring to different machines and browsers that store the cookies locally.

How do i actually use them

Cookies are accessible by all web programming languages. That means, javascript, python, php, and many more. First i want to go over using cookies with jQuery since it is the easiest way to do this.

jQuery has a plugin you use with the jQuery library itself and you can really easily store and access your cookies. So lets look at the code of storing and displaying a cookie.

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="jquery.cookie.js"></script>
<script>
$(document).ready(function(){
	// set cookie
	$.cookie('my_cookie_name', 'value inside of it');

	// get cookie
	alert($.cookie('my_cookie_name'));

	// delete cookie
	$.cookie('my_cookie_name', null);
});
</script>
</head>
<body>
<a class="setme">Set Me</a>
<a class="tellme">Tell Me</a>
<a class="delete">DeleteM</a>
</body>
</html>

Now let’s go over the important parts of the code. First of course we embed jQuery itself, then we add the jquery cookie plugin and then we start our beautiful jQuery code.

The set cookie is pretty straight forward, one line of code that will set the cookie “my_cookie_name” with the value “value inside of it”. We do that by passing in two parameters into our $.cookie() plugin. You do need the quotes around the name and the value of the cookie, feel free to use single or double quotes as your preference.

The get cookie code is even more straight forward we just pass in the cookie name in out jquery cookie plugin and it has the value we stored in there.

And finally deleting the cookie is almost the exact same as storing the cookie, only difference is we store null inside of it.

Now let’s go more advanced

Now that we have set a cookie, added a value, and deleted the stored value it’s time to do things like storing the cookie for a certain period of time, or to a certain date!

// cookie expires in 10 days
$.cookie('cookie_name', 'our value', { path: '/', expires: 10 });

// cookie expires in a set JavaScript Date
var date = new Date();
$.cookie('cookie_name', 'our value', { path: '/', expires: date });

The first code sets a cookie to expire in 10 days. That’s it… it’s as simple as that. Pass in a third parameter that has the path to where you want to store the cookie in the browser directory, leaving this to / is your best choice. And then you set the expiration days.

The second code we first set a variable date to store the current date and then it will set the cookie to expire to the certain JavaScript date. Putting a real date in there will not work unless you stored a javascript date in a variable called date. Read more about JavaScript dates here.

How to do this with JavaScript

Here is the code to write a cookie with plain JavaScript

function setCookie(key, value) {
   var expires = new Date();
   expires.setTime(expires.getTime() + 31536000000); //1 year
   document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
   }

function getCookie(key) {
   var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
   return keyValue ? keyValue[2] : null;
   }

setCookie('test', '5');
alert(getCookie('test'));

We set up two functions setCookie and getCookie. We need to pass in 2 variables into the setCookie the key and the value pair. Currenty the cookie is set to expire in a year but of course you can change that, i have the link on javscript dates above.

I hope i have shed some light on the world of cookies!

DZoneDiggDesign FloatDeliciousBlinklistRedditFacebookGoogle BuzzTwitterStumbleUponTumblrShare

Related posts:

  1. Associative Arrays – jQuery style JavaScript Functions
  2. How To: Jquery Scroll to Anchor and Scroll To Top (simple)
  3. jPaginate – jQuery Pagination System Plugin
  4. How To Create a jQuery Plugin
  5. Mock Design Slice HTML CSS JavaScript – Modern Approach to Creating Websites

Did you absolutely LOVE this article... share it!

Comments

  • Hey, great post. Thank you. Exactly what I was looking for, didn’t even know I can do it with jQuery. Makes even better.

    Thanks!

  • Glad you like it!

  • This is very helpful. I didn’t know much about how they worked or how to use them in my own things. Thanks for sharing.

  • thanks for sharing u helped a lot! i always get confused with cookies..

Leave your own!

Sponsors

freedcamp free project management

Popular Articles

fzilla file hosting