Cookies in JavaScript

Cookies in JavaScript

Cookies are variables stored on the visitor's (client's) computer. When the client's browser requests a page, cookies are also obtained. JavaScript can be used to create and retrieve cookie values. 

Cookies are often the most efficient way to remember and track preferences, purchases, commissions, and other information required to improve visitor and website statistics.

Example

  • For Name- The first time visitors arrive at your web page, they must fill in their name. The name is then stored in a cookie. The name is retrieved from the stored cookie. The next time visitors arrive at your page, they could get a welcome message like "Welcome John Doe!"
  • For Date- The first time a visitor arrives at your web page, the current date is stored in a cookie. The data is retrieved from the stored cookie. The next time visitors arrive at your page, they could get a message like "Your last visit was on Tuesday, September 04, 2013!"

How do Cookies Work in JavaScript?

The server sends some data to the visitor's browser as a cookie. If the browser accepts the cookie, it is stored as plain text in the visitor's hard drive. And when the visitor arrives at another page of your site, the browser sends the same cookie to the server for retrieval.

We can say a cookie is plain text data records of 5 variables

  1. Expire 
  2. Domain
  3. Path
  4. Secure
  5. Name=Value

Expire variable in cookies

The date the cookie will expire. The cookie will expire when the visitor quits the browser if this is blank.

Domain in cookies

The Domain is the name of our Website.

Path in cookies

The path to the directory or web page that sets the cookie. If you want to retrieve the cookie from any directory or page, this may be blank.

Secure in cookies

If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.

Name=Value in cookies

Cookies are set and retrieved in the form of key and value pairs.

So those are the main components of a cookie.

In JavaScript, we can manipulate the cookies using the cookie property of the document. Here we can "Read, Create, Modify, and delete" a cookie.

Syntax

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

Now let's do some Live Examples.

Storing Cookies in JavaScript

The simplest way to create a cookie is to assign a string value to the "document. cookie" object that looks like the syntax above.

<html>

<head>
    <script type="text/javascript">
        function writeCookie() {
            if (document.myform.customer.value == "") {
                alert("Enter some value!");
                return;
            }
            cookievalue escape(document.myform.customer.value) + ";";
            document.cookie = "name=" + cookievalue;
            alert("Setting Cookies :" + "name=" + cookievalue);
        }
    </script>
</head>

<body>
    <form name="myform" action="Give your Name Here">
        Enter name: <input type="text" name="customer" />
        <input type="button" value="Set Cookie" onclick="writeCookie();" />
    </form>

</html>

The output of storing the cookie will be.

Now we will provide a value for saving here, such as: "C-SharpCorner". 

Reading Cookies in JavaScript

It is similar to writing to them. Because the value of the "document. cookie" object is the cookie, you can use this string whenever you want to access the cookie. 

The "document.cookie" string will keep a list of "name=value" pairs separated by semicolons, where the name is the name of a cookie, and the value is its string value.

You can use the string's split() function to break the string into keys and values as follows,

<HTML> 
  <head>
    <script type="text/javascript"> function Readcookie()
      var allcookies document.cookie;
      alert("All cookies: " + allcookies );
      // Get all the cookies pairs in an array 
      cookiearray - allcookies.split(':');
      // Now take key value pair out of this array 
      for(var i=0; i<cookiearray.length; i++){
        name = cookiearray[i].split()
        value = cookiearray[i].split('-5[1];
                                     alert("Key is: " + name + and value is : + value);
      }
      }
    </script>
  </head>
  <form name="myform" action="">
    <input type="button" value="Get Cookie" onclick="ReadCookie()"/>
  </form>
  </body> 
</html>

When we run the code above, the browser will show the output as the following.

Now let's click on Get Cookie. That will show the output.

Our stored cookie is: "C-SharpCorner". And when we click on Om, it will show all cookies as the key is the name, and the value is: "C-SharpCorner". 

So now, let's try to delete it.

Try the given code.

Delete Cookies in JavaScript

Sometimes we want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, we must set the expiration date to the past.

Use the following code,

<html>
  <head>
    <script type="text/javascript"> function writeCookie()
      {
        var now new Date();
        now. setMonth( now. getMonth() - 1);
        cookievalue = escape(document. myform. customer.value) + document.cookie="name=" + cookievalue;
        document.cookie
        "expires" +now. toUTCstring() + " alert("setting Cookies : + "name" + cookievalue );
    </script>
  </head> 
  <body>
    <form name="formname" action="">
      Enter name: 
      <input type="text" name="customer"/>
      <input
             type="button" value="Delete Cookie" onclick="writeCookie()"/>
    </form> 
  </body> 
</html>

Instead of setting the date, see that the new time uses the setTime() function. The output for the code above will be,

By using the name, we can delete a specific cookie.

Summary

This article taught us about Cookies and how it works in JavaScript. Do more exercise and pingback your problems.


Foreantech
Foreantech - A complete online solution company.