Monday, 19 September 2011

Cookie - Create and Read in JavaScript

/* function to craete cookie */
function CreateCookie(name, value)
{
      var days = 7;
      var date;
      var expires;

      try
      {
            if (days)
            {
                  date = new Date();
                  date.setTime(date.getTime()+(days*24*60*60*1000));
                  expires = "; expires="+date.toGMTString();
            }
            else
            {
                  expires = "";
            }

            document.cookie = name + "=" + value + expires + "; path=/";           
      }
      catch(err){}

}



/* function to read cookie */
function ReadCookie(name)
{
      var nameEQ;
      var ca;
     
      try
      {
            nameEQ = name + "=";
            ca = document.cookie.split(';');

            for(var i=0; i<ca.length; i++)
            {
                  var c = ca[i];

                  while (c.charAt(0)==' ')
                  {
                        c = c.substring(1,c.length);
                  }
                 
                  if (c.indexOf(nameEQ) == 0)
                  {
                        return c.substring(nameEQ.length,c.length);
                  }
            }          
      }    
      catch(err){}
}

No comments:

Post a Comment