Software, Systems, and Solutions

"We do not run your business. We make your business run better."

Skip Repetitive Navigational Links

Cookies


  • A Cookie is a data file that is written on the user's computer by a program within a Web page.
  • Cookies are often used to store information about:
    • Which pages a user has viewed
    • How many times a user has visited a Web site
    • What information the user has entered on past visits (e.g. login name and password or customer data)
    • What items a user has selected to purchase (shopping cart)
  • A cookie stores information in pairs of variable names and associated values.  Each name/value pair is separated by a semicolon (;):
    userid=mkellog;password=hello;
  • Information in cookies is essentially private.  Cookies can only be read by the same Web site domain name or IP address that created them.

Temporary Cookies


  • Temporary cookies store information in the main memory of the user's computer and are only valid during the browser session in which they are created.
  • A cookie associated with an HTML document can be referenced using the cookie property of the document object (document.cookie).
  • For example: to create a cookie that temporarily stores a user name found in a textbox:

               

<!-- Form calls writeN, return false cancels
     default action of submit button -->

<form onsubmit="writeN(this);return false;">
  <input type=text name="txtName" size="30">
  <input type="submit" value="Write Cookie">
</form>

<script language="JavaScript">
<!--
function writeN(form)
{ // if textbox isn't empty write cookie 
  if (form.txtName.value != "")
    document.cookie = "name="+
             form.txtName.value + ";";
  else  // otherwise show error message
    alert("Error: Enter a name!");
}
// --->
</script>
  • The cookie string concatenates the name of the cookie variable ("name"), the equal sign (=), the name entered in the textbox (form.txtName.value) and the semicolon (;) that signifies the end of the name/value pair.
  • To read this cookie and display its contents just:
    alert(document.cookie);

Adding a second value to the cookie

  • You can store multiple values in a single cookie by appending the new cookie variable name and value to the end of the cookie:
    document.cookie = "[new_name]=[new_value];"

               

  • Programming Note: If you write a new value to the cookie using an existing name the new value will overwrite the old value.
  • Programming Note: You can store up to 20 name/value pairs in your cookie.  If you try to store more new ones will overwrite old ones.

Persistent Cookies


  • Persistent cookies store information in text files on the users workstation and are available after a user exits the current browser session.
  • Persistent cookies have an expiration date and are deleted from the system after a specific time interval.
  • All cookies for a given Web server are stored in the same file and each new cookie name/value pair is automatically added to the list of cookies already created by that server. 

Expiration Dates

  • To add an expiration date to a cookie you just add:
        expires=[date]
    The date attribute must be written in the following date format:
        day, dd-mm-yy hh:mm:ss GMT
  • The following function can be used to create a date string in the correct format.  It creates a Greenwich Mean Time date xDays days from the day the cookie value is set (xDays is the argument).

             

function getGMT(xDays)
{
   var exp = new Date();  // get current date 
   // get current time and add xDays*24hrs/day
   // *60min/hr*60sec/min*1000mSec/sec

   exp.setTime(exp.getTime() +  
              (xDays*24*60*60*1000));
   return exp.toGMTString();
}

Creating a Persistent Cookie

  • To create a persistent cookie that stores a user name and password you:

User Name:
Password:  
 

<!-- Form calls writeLogin -->
<script language="JavaScript">
<!--
function writeLogin(form, exp)
{ // if textboxes aren't empty 
  if (form.txtName.value != "" &&
      form.txtPass.value != "")
  {  
     // write name & expires 

     document.cookie = 
      "name=" + form.txtName.value + ";" +
      "expires=" + getGMT(exp) + ";";
     // write password & expires 
     document.cookie = 
       "password="+ form.txtPass.value + ";" +
       "expires=" + getGMT(exp) + ";";
  }
  else  // otherwise show error message
    alert("Error: Enter name & password");
}
// --->
</script>

Reading Values of Individual Cookie Variables

  • So far we have retrieved the entire contents cookie (all variable names and corresponding values).  In normal use each name/value pair is usually retrieved and processed individually.
  • The function getCookieValue(name) (below) is designed to return the value associated with a given cookie name:

function getCookieValue (name) 

 var arg = name + "=";
 var startName = document.cookie.indexOf(arg);
 var start = startName + arg.length;
 if (start != -1) // if cookie name exists
 {
  var end = 
      document.cookie.indexOf (";", start);
  if (end == -1)
      end = document.cookie.length;
  // the value from within the cookie
  return document.cookie.substring(start,end);
 } 
 else
  return null;
}
 
<form>
<input type="button" value="Show name" 
 onclick="alert(getCookieValue('name'));">
<input type="button" value="Show password" 
 onclick="alert(getCookieValue('password'));">
</form>
  • In the above code the value is the substring in the  cookie between start (the index where the value for the given cookie name begins) and end (where the given value ends).
    • start: get the indexOf where the name begins, then  add the length of the name & the equal sign (=) to that index value.
    • end: find the indexOf the first semicolon (;) following start.

Deleting Cookies

  • Occasionally you want users to be able to remove a cookie themselves (to clear their shopping cart for example).
  • To delete a cookie you need to reset its expiration date to some time before NOW and then the system will delete it automatically:

function deleteCookie (name) 

   var exp = getGMT(-1); 
   var cval = getCookieValue (name); 
   document.cookie = name + "=" + cval + 
            "; expires=" + exp + ";";
}

<input type="button" value="Delete" onclick=  
 "deleteCookie('name');alert(document.cookie);">

Cookies and Shopping Carts


  • One common use for cookies is to store information related to items a visitor plans to purchase on a given site.
  • These cookies are usually temporary cookies though sometimes they are persistent cookies with a very short expiration date (~1 hour).
  • When defining cookies for shopping carts, you need to determine what to put into your cookie.
    • Sample Cookie: cookie_name=pname|descript|quantity|price;

Set Shopping Cart Cookie

  • The cookie name is ShopCart and the value is the product data.
  • appendCookie checks if something is already in the cart, a delimiter (|) is added after the current cookie value and the new product data is appended to it.
  • setCookie creates a persistent cookie if days  is > 0 otherwise it creates a temporary cookie.
    (this cookie expires in 3 hours (.125 of a day). 

Zilly Zizz
A Silly Toy
$35.00

Filly Fizz
A Fizzy Froth
$12.99

function appendCookie (name, value, days, delim)
{ // get contents already in cookie
  var current = getCookieValue(name);

  // if something already in cookie 
  // add new value to the end it

  if(current != null)
    value = current + delim + value;

  // Set or Reset the cookie
  setCookie(name, value, days);
}

function setCookie (name, value, days)

  // Create a persistent cookie
  if (days > 0)
    document.cookie = name + "=" + value +  
            ";" + getGMT(days) + ";" ;
  // Create a temporary cookie
  else  
    document.cookie = name +"="+ value + ";";  
}

<input type="button" value="Buy It!" 
 onclick="appendCookie('ShopCart',
 'Zilly Zizz|A Silly Toy|1|35.00',.125,'|');">

Get Shopping Cart Cookie

  • The functions that read the shopping cart cookie must separate the individual pieces of data and place them in the proper location in the cart.
  • This is accomplished by splitting the string into and array of strings using the split() method for strings.
function getCartData(n, delim)
{
  var prods = getCookieValue(n); // cookie data  
  var nProd = 0;   // # of products
  var nVal = 4;    // # of values per product

  pnameA = new Array();    // arrays that store
  descriptA = new Array(); // product data
  quantityA = new Array();
  priceA = new Array();

  // if products have been selected
  if ( prods != null)
  {
    prods = prods.split(delim);
    nProd = prods.length/nVal; 

    // write data to data arrays
    for (var i=0, j=0; j < nProd; i+=nVal, j++)
    {
      pnameA[j] = prods[i];
      descriptA[j] = prods[i+1];
      quantityA[j] = parseInt(prods[i+2]);
      priceA[j] = parseFloat(prods[i+3]);
    }
  }    // After arrays complete display the cart

  writeCart(nProd, pnameA, descriptA,
            quantityA, priceA);
}
  • This function calls writeCart( ) to write the contents of the arrays to display the cart.
  • One example of a cart display function is shown below.  
    • It displays all the data in a table with the quantity in a textbox (so it could be updated).  
    • It has an update button (discussed later)
    • It does not display an extended price (price*quantity) for each product nor does it display a total for all the products.
    • It has no buttons to empty (clear) the cart or to Check-out!
    • It has no headings saying what is in each column.
function writeCart(nProd, pnameA, descriptA, 
          quantityA, priceA, name, delim)
{
 // Check if any products selected
 
if (nProd < 1)
   document.writeln("Your Cart is Empty");

 else
 { // put products in a table
   document.writeln("<center><table border=1>");

   // loop to write each product on a row
   // each data item in a separate cell
   for ( var j=0; j < nProd; j++)
   {
     document.writeln("<tr><td>" + pnameA[j]) ;
     document.writeln("<td>" + descriptA[j]) ;

     // write quantity to textbox
     // this allows user to change it 
 
    document.writeln("<td><input name=q");
           + j + " value=" + quantityA[j] "
           + "size=6>") ;

     // format price to have 2 decimal places 
     // and add a $ sign
     document.writeln("<td>$" + 
           formatFixed(priceA[j]) + "</tr>") ;
   }
   document.writeln("</table>");

   // Button to call an update cookie function
   // "updateCartCookie(form,name,delim,days)" 
   document.write('<input type="button"');   
   document.write('value="Update Cart"'); 
   document.write('onclick="updateCartCookie(');
   document.write("this.form,'" + name + "','");
   document.write(delim + "',.125);");
   document.write('window.location=');
   document.writeln('document.URL;">');
   document.writeln('</center>');
}
}


Update Cart

  • One more function that is useful is one that would allow you to change the quantities in the cart and update the cookie.
  • The update button on the cart calls a function that rewrites the 'ShopCart' cookie using values found in the quantity textboxes.
function updateCartCookie(form, name, del, exp)
{
          // product data from old cookie
  var prods = getCookieValue(name); 
  var nVal = 4;        // # values/product
  var cookieString= "";// Holds cookie value
  var nProd = 0;       // # products in cart

  // if products have been selected
  if ( prods != null)
  {
  prods = prods.split(del);
  nProd = prods.length/nval;

  // Create cookie string
  for (var i=0, j=0; j < nProd; i+=nVal, j++)
  { 
    // Get quantity from textbox
    var quant = form.elements[j].value;

    // if quantity is a number > 0
    if (quant != 0 && 
        parseInt(quant) != Number.NaN)
    {
      if (cookieString != "")
        cookieString = cookieString + del;

      cookieString = cookieString + prods[i]
           + del + prods[i+1] + del
           + quant + del + prods[i+3];
     }
  }
  if(cookieString != "")
  { // Overwrite old cookie w/ new values
    setCookie(name,cookieString,exp);
  }
  else // Nothing left in cart so delete cookie
    deleteCookie(name); 
  }
}

Shopping Cart Cookie Code

  • The Shopping cart cookie code discussed in today's lecture can be found in the JavaScript file:
    "cookieCart.js"
  • This code will work when cookies are set from one or more pages and read from another (the pages should be located in the same directory):
    cookie_set.html
    cookie_get.html

Portions of this page were obtained from:
Database Driven Web Sites
by Morrison & Morrison, Cambridge, MA: Course Technologies, 2000.