Javascript TUTORIAL


Javascript Cookies


Cookies are the data stored in your browser - that are used for future retrieval. For example, when you login, the username is stored in the cookie. So next time when you open the same website it retrieves the username from the cookie.

Javascript can be used to store and retrieve cookies. In this tutorial we will see how the cookies are stored and retrieved.

The document.cookie property


We have already used document object numerous times in the tutorial ( remember document.write ?). This time we will use another property of the object document - cookie.

Setting a cookie


Let us take a look at the following lines which will set the cookie.
document.cookie = "username= Heather;
                  expires=07/08/2008 00:00:00";


The "username" is the cookie name. "Heather" is the value of the cookie name.The "expires" property defines when the cookie will expire. In the simplest term, this is how the cookie will be set. Formally it has 3 more properties. The formal definition of document.cookie is as follows


document.cookie = "name=value; expires=date; path=path;
                   domain=domain; secure";


The first two of these properties have been discussed in the previous example. The path property is optional - it specifies a path within the site to which the cookie applies. Only documents in this path will be able to retrieve the cookie. The domain property is optional - Only websites in this domain will be able to retrieve the cookie. For this tutorial we will leave it blank. The secure property is an optional flag that indicates that the browser should use SSL when sending the cookie to the server. We will not use it in this tutorial ( this keeps the things simpler to learn - don't they ?)

Let us now write a function that will set a cookie. Take a close look at the following function


function setcookie(name,value,expire_d)
{

var cookie_str =  name + "=" + escape ( value );

if ( expire_d )
  {

    var expdate=new Date();
    expdate.setDate(expdate.getDate()+expire_d);
	
    cookie_string += "; expires=" + expdate.toGMTString();
  }

document.cookie = cookie_string;

}


The function setcookie will set the cookie for that will expire in number of days specified in expire_d. Since the value field may contain spaces semicolons etc, we escape our cookie values. Escapining encodes non-alphanumeric characters. This wull ensure that our browser can interpret the values properly. Escaping will ensure proper return - for values such as "Mary Beth". As an example escape("Mary Beth") will ensure proper return value.

If the expire_d variable is specified then the function gets the current day and adds the number of days in the current date and sets it as the expiry date of the cookie. In practice there is also a deletecookie kind of function which is called when, say, logout button is clicked.

Our aim is to design a page which will ask for our name when we visit the page for the first time. In the next visit it will not ask, but display our name - provided the cookie has not expired. We will need another function that will check if the cookie has been set. This function will be called immediately after the page loading. If the cookie is not set, it will prompt for user name. If the cookie is set it will retreive cookie and display it. Let is take a look at the following function.




function checkandgetcookie(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 "";
}



If the document.cookie object holds some cookies, then check to see if our specific cookie is stored. If our cookie is found, then return the value, if not - return an empty string.

Let us also write a function to delete a cookie. Usually, in the professional wesites, there is a logout button, which will delete the username and or password.


function deletecookie ( cname )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cname += "=; expires=" + cookie_date.toGMTString();
}

Putting it all togather



<html>
<head>
<script type="text/javascript">
<!--
/*
************************************************************
Example - Cookie
************************************************************
*/

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 "";
}

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.toGMTString());
}


function deletecookie ( cname )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cname += "=; expires=" + cookie_date.toGMTString();
}
</script>
</head>


<body>

 <h2> A simple cookie Tutorial </h2>

<script type="text/javascript">

username=getCookie('username');
if (username!=null && username!="")
  {
 document.write('Welcome again '+username+'!'+'<br>');
document.write ( "<a href=\"javascript:deletecookie('username');document.location.reload ( );\"> Del kuki</a>" );

 }
  else 
  {
  username=prompt('Please enter your name:',"");
  if (username!=null && username!="")
    {
    setCookie('username',username,365);
    }
  }
 </script>
<body>
</html>


You may like to copy paste the above code and try it yourself.