Friday, September 3, 2010

Working with Cookies

A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.

If c_name is the name of the cookie.

Creating Cookies:
Use the following function to create a cookie,

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

Reading Cookie Value:
You can the get the values of the cookie created in the first step using the following function. You just need to pass cookie name to this function,

function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}

Deleting Cookies:
Use the following function to delete a cookie. Just pass the name to the function,

function Delete_Cookie(c_name)
{
document.parentWindow.parent.document.cookie = name + "=" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

Always Search @ Fukat Ka Gyan: Hub For Quick Solutions

No comments:

Post a Comment