Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Use Cookies in JavaScript and HTML

This article will give us idea on how to use cookies in our websites for storing of information easily and making things fast.

Cookies can be used to store temporary data. It can be used to store information like id, token value, session variable, in shopping carts etc. The cookies are stored in browser and there values are retained till they are been cleaned out by user or by any other application or the cookie expires. It can help to remember user preference so that when user enters the site 2nd time the site is displayed according to his preference which is set when visited the site first.

The main problem in cookies is if cookies are disabled on a browser then sites functionality based on cookies is also gone. Secondly always remember that you must never store your password in cookies.

Here we are going to learn operations on cookies like creating a cookie, obtaining values from cookies.

Listing 1: Setting a cookie

function setCookie(c_name,value)
{
var expiry=new Date();
expiry.setDate(expiry.getDate() + 100);
document.cookie=c_name + "=" + escape(value);
}

Here:

  1. we set function named setCookie.It takes 2 parameters which is cookie name and the value of cookie.
  2. Now we define a variable named expiry and set a expiry date for the cookie. Here first we initialized expiry with today date. After that we added 100 days so that now the expiry date is after 100 days from today.
  3. Now we set the cookie using document.cookie and provided a value for the cookie.

Now we will learn how to return the value of the cookie.

Listing 2: Retrieving a cookie

function getCookie(c_name)
{
var i,x,y,cookies=document.cookie;
  x=cookies.substr(0,cookies.indexOf("="));
  y=cookies.substr(cookies.indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  
}

Here:

  1. We made a function named getCookie which take a parameter that is cookie name.
  2. Now we try to retrieve the cookie which we saved earlier
  3. Now we will separate the name and value of the cookie.

  4. The cookie name would be a substring from 0 and up to the first ‘=’.So we obtain the name of cookie and store it in variable x. The value of cookie is saved in variable y.
  5. Now we check whether the retrieved cookie is the one we have set earlier.
  6. If a match is found then the value of cookie is returned.

Listing 3: Checking cookie

function check()
{
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Hi " + username);
  }
else
  {
  username=prompt("Name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username);
    }
  }
}
 

Here:

  1. We defined a function which is dependent on existence of cookie.
  2. First it checks if the cookie exists. If it exists then it stores the cookie value and then display the same to the user.
  3. If the cookie does not exist then it will prompt the user to enter his name and then store that name in the cookie. So that the cookie now get saved in the browser and is available next time and the browser remember your session even when you close the website

Listing 4: Putting things all together

<html>
<head>
<title>csanuragjain</title>
<script type="text/javascript">
function getCookie(c_name)
{
var i,x,y,cookies=document.cookie;
  x=cookies.substr(0,cookies.indexOf("="));
  y=cookies.substr(cookies.indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  
}

function setCookie(c_name,value)
{
var expiry=new Date();
expiry.setDate(expiry.getDate() + 100);
document.cookie=c_name + "=" + escape(value);
}

function check()
{
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Hi " + username);
  }
else
  {
  username=prompt("Name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username);
    }
  }
}
</script>
</head>
<body onLoad="check()">
Cookie Demonstartion.
</body>
</html>
 

Here:

  1. Everything is same just we added all the scripts inside the script tag inside head tag.
  2. We call the check function on body load so that when the body is loading then check function checks the existence of cookie and retrieve value of cookie if it exist otherwise it will create a new cookie and set the various parameters for the cookie.

Advantage of cookies

  1. Cookies can be used to store small information. You can use it to store color preference of user.
  2. You can use it store small temporary values which can be used in the next page. Like you may use it store id selected by user and then when you move to another page then you can use this cookie to extract user preference and then work according to the value stored. This way you store the value locally on client browser and the request don’t have to come to server .This surely makes things faster.

Remember to make sure when using cookies

  1. First if browser has cookies disabled and your site critical functionality requires the use of cookie then site will fail to perform its work.
  2. Don’t use it to store confidential information because cookies can be altered easily and some browser allow to check cookie value. Atleast make sure if you store very important data in cookie then just encrypt that information in cookie value which will make it safe

This is all for today’s article. Hope you liked the article. See you next time with something more exciting.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login