Using cookies in JavaScript

Walden Systems Geeks Corner Using cookies in JavaScript tutorial programming Development Rutherford NJ New Jersey NYC New York North Bergen County
a high-level, interpreted programming language that conforms to the ECMAScript specification. It is a language that is also characterized as dynamic, weakly typed, prototype-based and multi-paradigm. Alongside HTML and CSS, JavaScript is one of the three core technologies of the World Wide Web.[9] JavaScript enables interactive web pages and thus is an essential part of web applications. The vast majority of websites use it,[10] and all major web browsers have a dedicated JavaScript engine to execute it.

Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. We may need to maintain session information among different pages For example, one user registration ends after completing many pages. In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics. Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client. The web server sends some data to the client browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. When the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server remembers what was stored earlier. Cookies are a plain text data record of 5 variable-length fields:

expires - The expiration date of the cookie, if none is set, cookie will expire when client quits the browser.

Domain - The domain name of our site.

Path - The path to the directory or web page that set the cookie, if blank, we can retrieve the cookie rom any page.

Secure - If set, the cookie can only be retrieved with a secure server ( HTTPS ), otherwise there is no restriction.

Name=Value - Cookies are set and retrieved by key-value pairs.

JavaScript can manipulate cookies using the cookie property of the Document object. Java script can read, create, modify and delete cookies much the same way PHP does except in PHP, the processing is done on the server.


Storing Cookies

The easiest way to create a cookie is to assign a value to the document.cookie object. Cookie values can't have semicolons, commas or white space. We can get around this by using the escape( ) function to encode the value before storing it in the cookie. We can use the corresponding unescape( ) function when we access the cookie value.

<html>
   <head>  
      <script type = "text/javascript">
            function WriteCookie() 
            {
               if( document.myform.fullName.value == "" ) 
               {
                  alert("Enter some value!");
                  return;
               }
               cookievalue = escape(document.myform.fullName.value) + ";";
               document.cookie = "name=" + cookievalue;
               document.write ("Setting name : " + "name=" + cookievalue );
            }
      </script>    
   </head>
   
   <body>      
      <form name = "myform" action = "">
         Enter full name: <input type = "text" name = "fullName"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
      </form>   
   </body>
</html>


Reading cookies

Reading a cookie is just as straight forward as writing one, because the value of the document.cookie object is the cookie. So we can use this string whenever we want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value. We can use Javascript's strings' split( ) function to break a string into key and values. In the example below, length is a method of Array class which returns the length of an array.

<html>
   <head>  
      <script type = "text/javascript">
            function ReadCookie() 
            {
               var allcookies = document.cookie;
               document.write ("All Cookies : " + allcookies );
               
               cookiearray = allcookies.split(';');
               
               for(var i=0; i>

Deleting a cookie

There is no function to delete cookies. We can delete cookies by using the same syntax that we use to create cookies except we set the expire date to the past. This is similar to the way PHP deletes cookies by using the setcookie( ) method with a expiration date in the past.

      <script type = "text/javascript">
            function DeleteCookie() 
            {
                document.cookie = "expires=Thu, 01 Jan 1970 00:00:01 GMT;"
            }
      </script>