[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Javascript cookie setting

Posted on 2006-05-19
3
Medium Priority
?
530 Views
Last Modified: 2012-05-05
When setting a cookie using perl/cgi you need to set the cookie in the header of the file you want the client to keep.  My question is while using javascript can you set a cookie at any time?  For example a person has loaded a page and while the page has clicked several buttons, after each button is pressed can one modify the cookie on the client machine?

Please provide an example.

Thanks very much for your help.  I have made this question worth 500 points as an example is needed.
0
Comment
Question by:ralphsauto
3 Comments
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16722180
Hi ralphsauto,

w3schools provides a simple example:
http://www.w3schools.com/js/js_cookies.asp

I belive javascript can set a cookie at any time, languages like perl/cgi I think only render the page for the client, but essentially they are only serverside so once the page is loaded by the client they have not further power.  Javscript, already on the client can now create and process events (clicking buttons stuff like that).

Joe P
0
 
LVL 41

Assisted Solution

by:HonorGod
HonorGod earned 800 total points
ID: 16722326
---------------------------------------- cookie.js ----------------------------------------
//--------------------------------------------------------------------
// Name: Cookies.js
// Role: Implementation of cookie object and methods
// From: JavaScript - The Definitive Guide 4th Edition
//       By David Flanagan
// ISBN: 0-596-00048-0
//--------------------------------------------------------------------

//--------------------------------------------------------------------
// Name: Cookie()
// Role: Constructor function
//       Creates a cookie object for the specified document, with the
//       specified name and optional attributes.
//
// Parameters/Arguments: [ R = Required, O = Optional ]
// [R] document - The Document object in which the cookie is to be
//                stored.
// [R] name     - A string specifying a name for the cookie.
// [O] hours    - Number of hours from now when the cookie should
//                expire.
// [O] path     - String specifying the cookie path attribute.
// [O] domain   - String specifying the cookie domain attribute.
// [O] secure   - Boolean value requesting a secure cookie.
//--------------------------------------------------------------------
function Cookie( document, name, hours, path, domain, secure ) {
  //------------------------------------------------------------------
  // All the predefined properties of this object begin with '$' to
  // distinguish them from other properties which are the values to
  // be stored in the cookie.
  //------------------------------------------------------------------
  this.$document = document;
  this.$name     = name;

  if ( hours ) {
    this.$expiration = new Date((new Date()).getTime() + hours * 3600000);
//  alert( 'Expires: ' + this.$expiration );
  } else
    this.$expiration = null;

  if ( path )
    this.$path = path;
  else
    this.$path = null;

  if ( domain )
    this.$domain = domain;
  else
    this.$domain = null;

  this.$secure = ( secure == true ) ? true : false;
}

//--------------------------------------------------------------------
// Name: store()
// Role: The store() method of the Cookie object.
//--------------------------------------------------------------------
Cookie.prototype.store = function () {
//alert( 'Cookie.store()' );
  //------------------------------------------------------------------
  // Loop through the properties of the Cookie object and put together
  // the value of the cookie.  Since cookies use the equals sign and
  // semicolons as separators, we'll use colons ':' and ampersands '&'
  // for the individual state variables we store within a single
  // cookie value.
  // Note: We escape the value of each state variable, in case it
  //       contains punctuation or other illegal characters.
  //------------------------------------------------------------------
  var cookieval = "";
  for ( var prop in this ) {
    //----------------------------------------------------------------
    // Ignore properties with names that begin with '$' and methods.
    //----------------------------------------------------------------
    if ( prop.charAt( 0 ) == '$' )
      continue;
    if ( typeof( this[prop] ) == 'function' )
      continue;
    if ( cookieval != "" )
      cookieval += '&';
    cookieval += prop + ':' + escape( this[ prop ] );
  }

  //------------------------------------------------------------------
  // Now that we have the value of the cookie, put together the
  // complete cookie string, which includes the name and the various
  // attributes specified when the Cookie object was created.
  //------------------------------------------------------------------
  var cookie = this.$name + '=' + cookieval;
  if ( this.$expiration )
    cookie += '; expires=' + this.$expiration.toGMTString();
  if ( this.$path )
    cookie += '; path=' + this.$path;
  if ( this.$domain )
    cookie += '; domain=' + this.$domain;
  if (this.$secure)
    cookie += '; secure';

  //------------------------------------------------------------------
  // Now store the cookie i.e., set the magic Document.cookie property.
  //------------------------------------------------------------------
    this.$document.cookie = cookie;
}

//--------------------------------------------------------------------
// Name: load()
// Role: Load() method of the Cookie object.
//--------------------------------------------------------------------
Cookie.prototype.load = function() {
//alert( 'Cookie.load()' );
  //------------------------------------------------------------------
  // Get a list of all cookies that pertain to this document.
  // Do this by reading the magic Document.cookie property.
  //------------------------------------------------------------------
  var allcookies = this.$document.cookie;
  if ( allcookies == "" )
    return false;

  //------------------------------------------------------------------
  // Now extract just the named cookie from that list.
  //------------------------------------------------------------------
  var start = allcookies.indexOf( this.$name + '=' );
  if ( start == -1 )
    return false;            // Cookie not defined for this page.

  start += this.$name.length + 1;  // Skip name and equals sign.
  var end = allcookies.indexOf( ';', start );
  if ( end == -1 )
    end = allcookies.length;

  var cookieval = allcookies.substring( start, end );

  //------------------------------------------------------------------
  // Now that we've extracted the value of the named cookie, we've got
  // to break that value down into individual state variable names and
  // values.  The name/value pairs are separated from each other by
  // ampersands, and the individual names and values are separated
  // from each other by colons. We use the split method to parse
  // everything.
  //------------------------------------------------------------------
  var a = cookieval.split( '&' ); // Break into name/value pairs.
  for ( var i=0; i < a.length; ++i )  // Break each pair into an array.
    a[ i ] = a[ i ].split( ':' );

    //----------------------------------------------------------------
    // Now that we've parsed the cookie value, set all the names and
    // values of the state variables in this Cookie object. Note that
    // we unescape() the property value, because we called escape()
    // when we stored it.
    //----------------------------------------------------------------
    for ( var i = 0; i < a.length; ++i ) {
        this[ a[ i ][ 0 ] ] = unescape( a[ i ][ 1 ] );
    }

    return true;             // We're done, so return the success code.
}

//--------------------------------------------------------------------
// Name: remove()
// Role: remove() method of the Cookie object - change expiration
//--------------------------------------------------------------------
Cookie.prototype.remove = function() {
  var cookie;
  cookie = this.$name + '=';
  if ( this.$path )
    cookie += '; path=' + this.$path;

  if ( this.$domain )
    cookie += '; domain=' + this.$domain;

  cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

  this.$document.cookie = cookie;
}
----------------------------------------------------------------------

...
  //------------------------------------------------------------------
  // This global variable is used to hold persistant information about
  // requester.
  // Note: Expires in 100 days (24 hours/day * 100 days = 2400 hours)
  //------------------------------------------------------------------
  var requester = new Cookie( document, 'CCrequester', 2400 );

  //------------------------------------------------------------------
  // Name: saveCookies()
  // Role: Store persistent information for user ID and preferences
  //------------------------------------------------------------------
  function saveCookies() {
    requester.field1     = document.getElementById( 'field1'   ).value;
    requester.field2    = document.getElementById( 'field1'  ).innerHTML;
    requester.field3     = document.getElementById( 'field3'   ).value;
 ...
    requester.store();
  }

  //------------------------------------------------------------------
  // Name: eatCookies
  // Role: Set expiration date for cookies to beginning of time
  //------------------------------------------------------------------
  function eatCookies() {
    requester.remove();
  }

  //------------------------------------------------------------------
  // Name: loadCookies()
  // Role: Retrieve persistent information for user
  //------------------------------------------------------------------
  // Cookie Attributes (fields):
  //   ESN     = Employee Serial Number
  //   Name    = Employee Name
  //   RID     = RETAIN ID
  //   addr    = Internet address
  //   phone   = User phone number
  //   contact = Contact preference (IM, e-mail, phone)
  //------------------------------------------------------------------
  function loadCookies() {
    var field = null;
    if ( requester.load() ) {
      field = document.getElementById( 'field1' );
      if ( requester.field1 ) {
        field.value = requester.field1;
      } else {
        return;
      }
      field = document.getElementById( 'field2' );
      if ( requester.field2 ) {
        field.innerHTML = requester.field2;
      }
      field = document.getElementById( 'field3' );
      if ( requester.field3 ) {
        field.value = requester.field3;
      } else {
        return;
      }
   ...
  }

0
 
LVL 29

Accepted Solution

by:
Pravin Asar earned 1200 total points
ID: 16722458
Here is my version of cookie tutorial. Hope you find this useful.

<html>
<head>
     <title>Cookies Tutorial by PravinAsar </title>
</head>

<body>

<script language="javascript">
// Delete cookie

function DeleteCookie(cookieName)
{
     if (!cookieName.length) {
           alert ('No cookie name specified');
          return;
     }
    // Get All cookies;
     var  ck = document.cookie;

     // append "=" to cookiename
     
     var  cn = cookieName + "=";
     
     // Get cookie
     
     var pos = ck.indexOf (cn);
     // Cookie found

     if (pos != -1) {
             // Set the start location for substring
             var start = pos + cn.length;
               // Get the end of cookie, start search from 'start' position.
               var end   = ck.indexOf (";", start);              
               // If end not found, set the end location equal to cookies length.
               if (end == -1) end = ck.length;
               //
               // Get Value of Cookies
               //
               var cookieValue= ck.substring (start, end);
               //alert ( "Cookie value : " + unescape (cookieValue));
               //create an instance of the Date object  
               var expDate = new Date();
               //set the date value to the past
               expDate.setTime(expDate.getTime() - 1000 * 60 * 60 * 24 * 365);
               //convert date to a GMT string
               expDate = expDate.toGMTString();
               // recreate cookie string              
               var cookieString = cookieName + "=" + cookieValue + ";expires=" + expDate;
               // update cookie
               document.cookie = cookieString;
     }
     return;
}

// this function gets the cookie, if it exists
function GetCookieValue(cookiename)
{
    // get all cookies
     
     var  ck = document.cookie;
     // append "=" to cookiename
     var  cn = cookiename + "=";
     // search for cookie
     var pos = ck.indexOf (cn);
     // if found
     if (pos != -1) {
             // set start location
             var start = pos + cn.length;
               // Get the end of cookie, start search from 'start' position.
               var end   = ck.indexOf (";", start);
               // If end not found, set the end location equal to cookies length.              
               if (end == -1) end = ck.length;
               //
               // Get Value of Cookies
               //
               var cookieValue= ck.substring (start, end);
               //
               // Write the current document.
               //
               //document.write  ( "<br>Cookie value : " + unescape (cookieValue));
     }
     return;
}

function GetCookies() {
    // Get cookies
     var  ck = document.cookie;
     var  ix=0;
     //
     // split the cookie string at ";"
     //
     var strs = ck.split (';');
     for (ix=0; ix <strs.length; ix++) {
          //document.write ("<br><br>Cookie " + ix + " " + unescape(strs[ix]));
          //split current strs[ix] at "="
          var ckvar= strs[ix].split('=');
          //
          // Write the current document.
          //
          //document.write ("<br>Cookie Name " + ckvar[0]);
          //
          // Get cookie value;
          //          
          GetCookieValue(ckvar[0]);
     }
     return ;
}


function set_Cookie (name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

function SetCookie(cookieName,cookieValue,nDays) {
     if (!cookieName.length)
     {
          alert ('No cookie name specified');
          return;
     }
    // Initialize date variable
     var today = new Date();
     var expire = new Date();
     // Validate input nDays
     if (nDays==null || nDays < 1 ) nDays=1;
     //
     // Add time to expire variable, it is milliseconds *hour
     // 1 day has 24 hours , 1 hour has 3600000 milliseconds;
     //
     expire.setTime(today.getTime() + 3600000*24*nDays);
      document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

function GetAndDeleteCookies() {
    // Get cookies
     var  ck = document.cookie;
     var  ix=0;
     //
     // split the cookie string at ";"
     //
     var strs = ck.split (';');
     for (ix=0; ix < strs.length; ix++) {
          //document.write ("<br><br>Cookie " + ix + " " + unescape(strs[ix]));
          //split current strs[ix] at "="
          var ckvar= strs[ix].split('=');
          //
          // Write the current document.
          //
          document.write ("<br>Deleting Cookie Name " + ckvar[0]);
            //
          // Delete Cookie
            //
          DeleteCookie(ckvar[0]);
     }
     return ;
}

</script>

<form action="cookie.htm" method="post">
COOKIE NAME:<input type="text" name="cookiename" value="">
<br>
COOKIE VALUE:<input type="text" name="cookievalue" value="">
<br>
<input type="button" value="Set Cookie" onClick="SetCookie(this.form.cookiename.value, this.form.cookievalue.value,1);">
<input type="button" value="Delete Cookie" onClick="DeleteCookie(this.form.cookiename.value);">
<br><input type="button" value="Inquire All Cookies" onClick="GetCookies();">
<br><input type="button" value="Delete All Cookies" onClick="GetAndDeleteCookies();">
</form>
<script language="javascript">
GetCookies();
</script>
</body>
</html>
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question