Cookies using JavaScript
Posted by Anandhan Subbiah on May 3, 2007 in Programming Concepts, Technical Articles • No commentsHTTP is a stateless protocol . Sessions help maintain state .Cookies help maintain session . Cookies are created by the server and stored on the client’s Browser. Everytime the client makes a request the browser attaches the cookie information along with the request , So the server will know that the request is coming from a certain browser/user.
Each domain may have only 20 cookies. The example below creates two cookies.
There is a 4KB limit on the amount of information one domain can store using cookies. That’s just over 4,000 characters which is actually a lot.
A website can set and read only its own cookies for e.g www.anandhansubbiah.com can’t read the cookie set by www.yahoo.com .
A web page can only read cookies that it set . For other pages in the same domain to read the cookie you have to add “path=/;” to the cookie. Also if you have subdomains like movies.anandhansubbiah.com you have to set the domain name so all subdomains can read the cookies.
You can also set the duration of the cookies using “expires=Fri, 21 Dec 2012 00:00:00 UTC;”
Cookies can hold key-value pairs.One of the important points to remember when writing and reading cookies is that cookie values can’t include spaces, commas, or semicolons. Happily, the escape() and unescape() functions will code and decode cookies, so you don’t have to worry about this restriction.
Here is a code snippet to read and write cookies using JavaScript. The logic is quite simple there is one value in the cookie called mycookie. mycookie has 3 pairs of information name , age and phone. They are delimited by a “/” and each key value is delimited by “~”
function setCookie()
{
var the_cookie = “username~anandhansubbiah/age~0/phone~123″;
var the_cookie = the_cookie + “path=/;”;
var the_cookie = the_cookie + “domain=anandhansubbiah.com;”
var the_date = new Date(”January 1, 2008″);
var the_cookie = the_cookie + “expires=” + the_date.toUTCString() + “;”;
document.cookie = “my_cookie=” + escape(the_cookie);
document.cookie = “second_cookie=” + escape(”second cookie”);
}
function readCookie(return_val)
{
var the_cookie = document.cookie;
var the_cookie = unescape(the_cookie);
var broken_cookie = the_cookie.split(”=”);
var the_values = broken_cookie[1];
var separated_values = the_values.split(”/”);
var property_value = “”;
for (loop = 0; loop < separated_values.length; loop++)
{
property_value = separated_values[loop];
var broken_info = property_value.split(”~”);
var the_property = broken_info[0];
var the_value = broken_info[1];
return_val[the_property] = the_value;
}
}
Then you can use the functions in your page as
var my_cookie = new Array();
readCookie(my_cookie);
document.write(”Name: ” + my_cookie["name"] + “”);
document.write(”Age: ” + my_cookie["age"] + “”);
document.write(”Phone: ” + my_cookie["phone"] + “”);
