fbpx
April 6, 2020
javascript cookie

JavaScript Cookies | Learn How To Structure Cookies Using JavaScript

In this tutorial we will be discussing about JavaScript Cookies which entails how to structure cookies on your web pages using JavaScript. In our previous tutorial we discussed about JavaScript event and we explained how to connect HTML events with JavaScript functions. If you haven’t gone through the tutorial you can do so using the link below

Read previous tutorial on: JAVASCRIPT EVENT | Learn How To Structure Events Using JavaScript

JAVASCRIPT COOKIES  

Cookies are used to efficiently track user’s information and activities on a web site. Cookies can be used to track purchases, visitor site statistics, preferences which helps the visitor get a better site experience. Sometimes you might have noticed that items you forgot to checkout on an eCommerce website still exist in the site order basket after few days. Such activity can only be carried out with the help of cookies.

HOW DOES COOKIES WORK?

When a visitor lands on a web page for the first time, the web page server sends in some data to the visitor’s web browser in form of cookie. The browser may either accept or reject the cookie. If it does accept the cookies, the cookie is then stored in the visitors hard drive. When the visitor navigates to another web page on the server, the browser sends back same cookie to the server for retrieval. Ones the server retrieves and goes through the cookie data, it remembers fully what was stored earlier on the users browser and the users activitiy

Cookies contain 5 different variables and they include:

  • Domain: This is the domain name of the server
  • Path: the path where the cookie was set
  • Expires: the date the cookie will expire
  • Secure: this is used to set whether the cookie should be retrieved by a secure server
  • Name=value: Cookies are stored and retrieved using key-value

With the help of JavaScript, developers can create, read, modify and delete cookies on a web page

Storing cookies

The syntax for creating a cookie is shown below

document.cookie = "key1 = value1;key2 = value2;key3 = value3;expires = date";

The above syntax is the simplest way cookie can be created by just assigning a string to the document.cookie . The “expires=date” property is used to set the date for the cookie to expire.

When creating and storing values in cookies, its fairly advice able to use the escape() function to encode value before storing it in the cookie. If you do this you will also need to use the unescape() function to read the values stored in the cookie.

EXAMPLE SHOWN BELOW

<html>
   <head>   
      <title>STORING COOKIES</title>
      <script type = "text/javascript">
         
            function alertEmptyCookie() {
               if( document.cookieForm.customer.value == "" ) {
                  alert("values are needed");
                  return;
               }
               cookievalue = escape(document.cookieForm.customer.value) + ";";
               document.cookie = "name=" + cookievalue;
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         
      </script>      
   </head>
   
   <body>      
      <form name = "cookieForm" action = "" method="GET"> 
         Enter a value: <input type = "text" name = "customer"/>
         <input type = "button" value = "Setting Cookie" onclick = "alertEmptyCookie();"/>
      </form>   
   </body>
</html>

RESULT

STORING COOKIES
Enter a value:

READING COOKIE

After writing a cookie structure the next thing that comes in is reading the cookie. Recall that the document.cookie is used to store a list of name=value pairs which will be separated by a “;” sign and strings can be broken into key and value using a split() function.

Example

<html>
   <head>   
      <title>Reading cookies </title>
      <script type = "text/javascript">
        
            function cookieReader() {
               var totalcookies = document.cookie;
               document.write ("All Cookies : " + totalcookies );
               
               
               cookiearray = totalcookies.split(';');
               
               
               for(var j=0; j<cookiearray.length; j++) {
                  name = cookiearray[j].split('=')[0];
                  value = cookiearray[j].split('=')[1];
                  document.write ("Key is : " + name + " and Value is : " + value);
               }
            }
         
      </script>      
   </head>
   
   <body>     
      <form name = "cookieform" action = "">
         
         <input type = "button" value = "Display Cookie" onclick = "cookieReader()"/>
      </form>      
   </body>
</html>

RESULT

Reading cookies

STRUCTURING THE COOKIE EXPIRY

When we explained the syntax of setting cookies we talked a little about the expiry. We can set the expiry date of a cookie ahead of that of the browsers session. This means that when the user shuts down the browser or web page the cookie will still be valid. Example shown below

<html>
   <head> 
      <title>COOKIE EXPIRY </title>  
      <script type = "text/javascript" name="javascript">
        
            function cookieFunct() {
               var now = new Date();
               now.setMonth( now.getMonth() + 1 );
               cookievalue = escape(document.myform.datavalue.value) + ";"
               
               document.cookie = "name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write (" Cookies : " + "name=" + cookievalue );
            }
         
      </script>      
   </head>
   
   <body>
      <form name = "myform" action = "">
      Input name: <input type = "text" name = "datavalue"/>
         <input type = "button" value = "Setting Cookie" onclick = "cookieFunct()"/>
      </form>      
   </body>
</html>

Deleting Cookie

The below illustration shows how to delete a cookie in javascript

<html>
   <head> 
      <title>COOKIE EXPIRY </title>  
      <script type = "text/javascript" name="javascript">
        
            function cookieFunct() {
               var now = new Date();
               now.setMonth( now.getMonth() - 1 );
               cookievalue = escape(document.myform.datavalue.value) + ";"
               
               document.cookie = "name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write (" Cookies : " + "name=" + cookievalue );
            }
         
      </script>      
   </head>
   
   <body>
      <form name = "myform" action = "">
      Input name: <input type = "text" name = "datavalue"/>
         <input type = "button" value = "Setting Cookie" onclick = "cookieFunct()"/>
      </form>      
   </body>
</html>

RESULT

COOKIE EXPIRY
Input name:

The above example shows how cookies are deleted by setting the date behind by one month

CONCLUSION

This article covers only the basic aspect of JavaScript cookies structuring, we strongly advice you look through other books and platforms for more information.

NEXT TUTORIAL: JAVASCRIPT PAGE REDIRECT

Leave a Reply

Your email address will not be published. Required fields are marked *