Please enable Javascript for better experience...
Create, Update and Get cookie value through javascript
By Rahul Kumar Jha | Dec 31, 2014 | In Articles | Update: Jun 12, 2016 | Total Views [ 21184 ]
Taged In
(8 Like)
Rate

In this article I will try to explain, how can we create, get or delete cookie value in javascript.

Introduction

We generally use cookie in web applications to store information and we are well aware how to do this with server side code. In this article I will explain, how can we get or set cookie values in javascript. It is not a tough job but need only a little trick. Here I will show, how we can create cookies in server side and get in javascript and also how can we perform all these activities in javascript itself.

Code

Before start, let's see how can we create cookie in c#. We use HttpCookie class to do this. Follow below step to create a cookie.

  • Create a cookie. Name it.
  • Set it's value.
  • Set expiry duration.
  • Add to cookie collection
            HttpCookie myCookie = new HttpCookie("mycookie");
            myCookie.Value = "I found value";
            myCookie.Expires = DateTime.Now.AddHours(1);
            Response.Cookies.Add(myCookie);

You can retrieve cookie value on server side with this simple line of code.

var cookie = Request.Cookies["myCookie"].Value;

If you want to edit/modify the value of cookie, you can do with this simple line of code.

Request.Cookies["myCookie"].Value = "Changed value of cookie.";

Below code add, read and edit a cookie.

        void SampleCookie()
        {
            var cookie = "";
            if (Request.Cookies["myCookie"] != null)
            {
                cookie = Request.Cookies["myCookie"].Value;
                Request.Cookies["myCookie"].Value = "changed value";

            }
            else
            {
                HttpCookie myCookie = new HttpCookie("mycookie");
                myCookie.Value = "I found value";
                myCookie.Expires = DateTime.Now.AddHours(1);
                Response.Cookies.Add(myCookie);
            }
            cookie = Request.Cookies["myCookie"].Value;

        }

Now let's see how can we do this with javascript one by one. If you have added javascript on page then you can also access cookie value in ASP.NET or MVC project with this code.

<script type="text/javascript">
    var cookie = '@HttpContext.Current.Request.Cookies["mycookie"].Value';
    alert(cookie);
</script>

Else, if you are using js file to perform javascript or using simple html then see below code.

Setting Cookie

We can set/get cookie with the help of document.cookie. In below function I have put cookie expiry to 2 hours.

document.cookie = cookieName + "=" + cookieValue + "; " + cookieExpireDate;

    function setCookieValue(cookieName, cookieValue) {
        var d = new Date();
        var hour = 2;
        d.setTime(d.getTime() + (hour * 60 * 60 * 1000));
        var cookieExpireDate = "expires=" + d.toString();
        document.cookie = cookieName + "=" + cookieValue + "; " + cookieExpireDate;
    }

Getting Cookie

You can play with cookie on client side using javascript document.cookie. Below is the code.

    function getCookieValue(name) {
        cookieList = document.cookie.split('; ');
        cookies = {};
        for (i = cookieList.length - 1; i >= 0; i--) {
            cookie = cookieList[i].split('=');
            cookies[cookie[0]] = cookie[1];
        }
        return cookies[name];
    }

Deleting Cookie

We can also delete cookie. Deleting cookie means, we change its expiration to a time that is not accesible. Let's see how to do this.

    function deleteCookieValue(cookieName) {
        var d = new Date();
        d.setTime(d.getTime());
        var cookieExpireDate = "expires=" + d.toString();
        document.cookie = cookieName + "=expired;" + cookieExpireDate;
    }

Implemention

Let's implement this in code.

    //This will create cookie named jcookie and will store in document.cookie
    var createCookie = setCookieValue("jcookie", "test user");
    //This method will return cookie value
    var cookie = getCookieValue("jcookie");
    alert(cookie);

    //This method deletes cookie.
    deleteCookieValue("jcookie");

Hope this helps you. Use it in your code and enjoy. I will come up with such more articles soon.

Share this

About the Author

Rahul Kumar Jha
Rahul Kumar Jha
Founder, Developer dotnet-concept.com

Public profile: user/profile/99900001


Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, ANGULAR, ANGULAR JS, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

User's Comments


 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment
 
 
 
 
 
 
Sponsors