blog

Home / DeveloperSection / Blogs / Cookies in JavaScript

Cookies in JavaScript

Danish Khan 3367 06-Oct-2012
Introduction:

In this blog I am going to explain what cookies are and why they are used in Java Script.

Why we need Cookie:

HTTP (Hyper text Transfer Protocol) which is responsible for  transfer of web pages to the user’s end and transferring user requests to the server is a state-less protocol, which means it does not remembers anything after it submits the page to the browser or to the server, so there are no concept of memory. But Cookie removed the drawback of HTTP by enabling us to store the information and use it for the second time.

                Cookies are small text file which are stored at the browsers end for storing user preferences as soon as he logs-in to the server for the first time. This file will be send to the server when user logs in to server for the second or successive number of time.

Example of Cookies:

Name Cookie: For the first time user is visiting the web site user will fill his name, that name will store in the cookie and will be there on the client-side and when the user logs in for the second time he will get a message displaying his name for eg: Welcome! Abhishek

Date Cookie: When user arrives to the web site the current date gets store in a cookie and when he visits the second time he will get the date displayed when he logged in to the website previously.

Cookie were originally developed for the CGI programming, but we can also use  Java Script for creating, modifying, deleting cookies with the help of Cookie property of the Document object.         

Cookies are set and retrieved in the form of key value pairs. Many Browsers provide to manage cookies, we can delete cookies we want from our browser. Cookies that contain very important information should be deleted from the user system.

There are five variable length fields in cookies:

1.       Expires: It sets the time when the cookie will expires, If the user has not set any time then the cookie will expire as soon as the browser closes.

2.       Domain Name : It is the Domain Name of the site.

3.       Path : It is the Path to the directory or web page that sets the cookie.

4.       Secure : If this field is set to ‘secure’ then it will only be retrieved from the secure server only.If user has not specified it then there are no restriction.

5.       Name Value Pair: Cookies are set as a name value pair, there is the name of the cookie and the value assigned to it.

Example of Creating Cookies:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript">
        function mycookies() {
            if (document.form1.txtCookieName.value == "") {
                alert("Enter name!");
                return;
            }
            cookievalue = escape(document.form1.txtCookieName.value) + ";
            document.cookie = "name=" + cookievalue;
            alert("Cookies Saved as: " + "name=" + cookievalue);
        }
</script>
</head>
<body>
    <form name="form1" action="">
    <div>
   <input id="txtCookieName" type="text" /><input id="btnCreateCookie" type="button"   value="Create Cookie" onclick="mycookies();" />
    </div>
    </form>
</body>
</html>

In this example I created a cookie by assigning a string value for example, name to the document.cookie object.  Escape function is used to encode the value before it is saved in the cookie.

How to Retrieve Cookie which was previously saved:

<html>
<head>
<script type="text/javascript">
<!--
    function ReadCookieValue() {
        var allcookies = document.cookie;
        alert("All Cookies : " + allcookies);
        cookiearray = allcookies.split(';');
        for (var i = 0; i < cookiearray.length; i++) {
            name = cookiearray[i].split('=')[0];
            value = cookiearray[i].split('=')[1];
            alert("Key is : " + name + " and Value is : " + value);
        }
    }
-->
</script>
</head>
<body>
<form name="form1" action="">
<input type="button" value="Get Cookie" onclick=" ReadCookieValue()"/>
</form>
</body>
</html>

 There can be a list of name-value pairs in the document.cookie object separated by semicolons; we have used split function to break a string in to key value pairs.

Conclusion:  In this blog I have shown you how to create and read the value of created cookie, because cookies are used by most of the websites they are very important part in Javascript.

 

 


Updated 18-Sep-2014

Leave Comment

Comments

Liked By