Cookies

A cookie is a small piece of information (a string with key/value pair) stored to the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. It can be accessed any time the viewer returns to your site, provided the cookie hasn’t been deleted or expired.
If the viewer doesn’t accept cookies, then a cookie won’t be able to be set or referenced later.
Cookies have some significant limitations:

1. Creating cookie

To create / set a cookie, just assign the name and value to document.cookie property, in the following format:
document.cookie = "name=value";
- You can’t have spaces, commas, or semicolons inside the string.

You can set only one cookie at a time, but assigning another value or multiple values to document.cookie doesn’t overwrite the previous cookies, unless one of them shares the same name. You can continue to assign name/value pairs to document.cookie until the 4KB limit.
<script type="text/javascript"><!--
// Setting a cookie
document.cookie = "name1=value1";

// Adding another cookie
document.cookie = "name2=value&name3=value3";
--></script>
- As you can see, the value of the cookie is being formatted in name=value pairs, and each pair is separated with an ampersand (&).
- But, you can choose any type of separators you want. The following code is fine as well:
<script type="text/javascript"><!--
document.cookie = "name2=value|name3=value3";
--></script>

• Becouse you can't use spaces, commas, or semicolons in cookies, you should always pass the value part of the string through encodeURIComponent() to make sure you use URI-safe characters.
<script type="text/javascript"><!--
var cookie_val = "string value";
document.cookie = "cookie_name=" + encodeURIComponent(cookie_val);
--></script>

• A cookie can also have some optional parameters. The complet syntax is:
name=value; expires=expirationDateGMT; path=URLpath; domain=siteDomain; secure
- Only the name and the value are required, the other parameters are optional; described below:
    expires - The date on which this cookie expires. This must be in GMT format.
          Ex.:   expires=Sat, 11 Mar 2012 18:32:02 GMT;
    path - Restricts access to the cookie to a portion of the site. If not specified, the cookie will be available to all pages of the site.
          Ex.:   path=/;
    domain - The domain or subdomain that can read that cookie.
          Ex.:   domain=courseseweb.net;
    max-age - A maximum age in seconds for the cookie, after which period the cookie will expire.
          Ex.:   max - age=3600 Specifies a maximum age in seconds for
    secure - If set, the browser will send that cookie over HTTPS only for security.
          Ex.:   secure
You can set any of these parameters by appending them to the cookie string, separated by semicolons.
<script type="text/javascript"><!--
// This secure cookie will last 6 months
document.cookie = "name=value;max-age=" + (60*60*24*183) + ";secure;";
--></script>

The following function can be used to set a cookie with all parameters.
<script type="text/javascript"><!--
function setCookie(name, value, expires, path, domain, secure) {
  var expString = ((expires == null) ? "" : ("; expires=" + expires.toGMTString()));
  var pathString = ((path == null) ? "" : ("; path=" + path));
  var domainString = ((domain == null) ? "" : ("; domain=" + domain));
  var secureString = ((secure == true) ? "; secure" : "");
  document.cookie = name + "=" + encodeURIComponent(value) + expString + pathString + domainString +secureString;
}
--></script>
- The expiry date (expires) must be set in milliseconds. For example, if we want the cookie last one week: expires=7*24*60*60*1000
- The toGMTString() method is needed to format 'expires' as a proper GMT date.
- To use this function, call it with any parameters you want to set up and use the word "null" for the parameters that are not used.
- For example:   setCookie('fruit', 'apple', 604800000, null, null);

2. Reading cookies

To read cookie, you need to get the value of the document.cookie property from the browser.
var mycookie = document.cookie;
Example:
<script type="text/javascript"><!--
// set the cookie
var cookie_val = "cookie_value";
document.cookie = "a_name=" + encodeURIComponent(cookie_val);

// get the cookie
var the_cookie = document.cookie;
alert(decodeURIComponent(the_cookie));       // a_name=cookie_value;
--></script>
- But, with just that you'll get a string with all the cookies in the current document.
- To read a specific cookie back, you have to break the string up on the semicolons and look at each name/value pair until you find the one you’re looking for.
To simplify finding a value from a cookie, you can use a function as in the following script:
<script type="text/javascript"><!--
function GetCookie (name) {
  var result = null;
  var myCookie = " " + document.cookie + ";";        // all cookie strings starts with a space and ends with ;
  var searchName = " " + name + "=";       // looks for what it's between name and the next '='
  var startOfCookie = myCookie.indexOf(searchName);
  var endOfCookie;
  if (startOfCookie != -1) {
    startOfCookie += searchName.length;
    endOfCookie = myCookie.indexOf(";", startOfCookie);
    result = decodeURIComponent(myCookie.substring(startOfCookie, endOfCookie));
  }
  return result;
}

var cookie_val = getCookie('cookie_name');         // gets the value of the cookie with the name 'cookie_name'
document.write(cookie_val);         // writes the 'cookie_val' value
--></script>

3. Deleting cookie

To delete a cookie, simply have it expire immediately by setting expire to some time before the current time.
If you specified a domain and path for the cookie, you have to do the same when you delete it:
<script type="text/javascript"><!--
function delCookie(name) {
  var ThreeDays = 3*24*60*60*1000;
  var expDate = new Date();
  expDate.setTime (expDate.getTime() - ThreeDays);
  document.cookie = name + "=ImOutOfHere; expires=" + expDate.toGMTString();
} 
--></script>
- Just call the function: delCookie('cookie_name');.

4. Example of using cookies

To understand better what cookies do, how to create and use cookies, study the following example.
It's a more complex example, includes a script with several functions that contain many of the elements presented in this lesson.
The purpose of this example is to understand how the cookies works. It contains a JavaScript script that has four functions for working with cookies, and a table with 2 columns, the first has a form that use the JS script to save some preferences in a cookie, and the second column contains a button that activates the display the preferences saved in cookies, and another button to delete cookies.
Here is rhe complete code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Example using cookie</title>
<script type="text/javascript"><!--
// function to set the cookie
function SetCookie () {
  // variabiles that gets the form values
  var culoare = document.prefers.culoare.value;
  var fructe = document.prefers.fructe.value;
  var citat = document.prefers.citat.value;

  // Set the expiration time, 2 days
  var twoDays = 2*24*60*60*1000
  var expDate = new Date()
  expDate.setTime(expDate.getTime()+twoDays);

  // Create the cookies
  document.cookie = "cookie1" + "=" + escape(culoare) + "; expires=" + expDate.toGMTString() ;
  document.cookie = "cookie2" + "=" + escape(fructe) + "; expires=" + expDate.toGMTString() ;
  document.cookie = "cookie3" + "=" + escape(citat) + "; expires=" + expDate.toGMTString() ;
}

// This function checks if exist the cookie with the name passed in the argument
// If that cookie exists gets and return its value
  function checkCookie(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));
    }
  }
  // If the cookie not exists
  return "You have not yet added a preference";
}

// This function gets the cookie values from the checkCookie() and stores them in an array
// Dysplays it the page the cookie values
function getCookie() {
  nr = getCookie.arguments.length

  var val_c = new Array(nr)
  var a = 0

  for (var i=0; i<nr; i++) {
    valoare=checkCookie(getCookie.arguments[i]);
    if (valoare!=null && valoare!="") {
    val_c[a] = valoare;
    a++
    }
  }

  // Dysplays the cookie values, at the indicated id
  document.getElementById("idculoare").childNodes[0].nodeValue = val_c[0];
  document.getElementById("idfructe").childNodes[0].nodeValue = val_c[1];
  document.getElementById("idcitat").childNodes[0].nodeValue = val_c[2];
}

// This function deletes the cookies
function delCookies() {
  nr_c = delCookies.arguments.length
  var ThreeDays = 3*24*60*60*1000;
  var expDate = new Date();
  expDate.setTime (expDate.getTime() - ThreeDays);

   for (var n=0; n<nr; n++) {
    document.cookie = delCookies.arguments[n] + "=DataDel; expires=" + expDate.toGMTString();
  }
}
--></script>
</head>
<body>
<table border="1" bordercolor="#8888fe" width="580" cellpadding="2" cellspacing="0">
  <tr><td>
  <form name="prefers">
    Write your favorite color:
    <input type="text" name="culoare" size="20" maxlength="40" /><br /><br />
    Write your favorite fruit:
    <input type="text" name="fructe" size="20" maxlength="40" /><br /><br />
    Write a favorite phrase:<br />
    <input type="text" name="citat" size="40" maxlength="80" /><br /><br />
    <input type="button" value="Favorite" name="buton" onclick="SetCookie()" />&nbsp;
    <input type="reset" value="Reset" name="reset" />
  </form>
  </td><td>
  <form name="prefers2">
    <input type="button" value="Show Favorites" name="buton" onclick="getCookie('cookie1', 'cookie2', 'cookie3')" />&nbsp;
    <input type="button" value="Delete cookie" name="Clear" onclick="delCookies('cookie1', 'cookie2', 'cookie3')" />
  </form>
  <b>Favorite color - </b><span id="idculoare"> </span><br />
  <b>Favorite fruit - </b><span id="idfructe"> </span><br />
  <b>Favorite phrase - </b><span id="idcitat"> </span><br />
  </td></tr>
</table>
</body>
</html>
- After you add this code in an HTML document, the browser will display the following result:
Write your favorite color:

Write your favorite fruit:

Write a favorite phrase:


 
 
Favorite color -
Favorite fruit -
Favorite phrase -
- First, press the "Show Favorites" button, will be displayed error messages, that you have not yet added a preference.
Fill in the text boxes at the left and then click "Favorite", it calls the "setcookie()" function that will store them in cookies that will expire in two days.
Click on "Show Favorites", it calls the "getCookie()" function, this will ged the data from cookies and will display the preferences you have added.
You will see the importance and advantage of cookies after that.
Close the broweser and it reopen this page and click "Show Favorites". Will be displayed your preferences added earlier. Tomorrow, if you come back to this page will see the same preferences, without having to write them again. These data are stored in cookies, and will be automatically deleted after two days.
If you want to delete these cookies earlier, click on the "Delete Cookis", it calls the function "delCookies()" that will delete them.