Setting and Getting Cookies using jQuery cookie example

Cookies are small piece of textual information stored in client's browser for various tracking purposes. Real time scenarios wher...


Setting and Getting Cookies using jQuery Cookie plugin

Cookies are small piece of textual information stored in client's browser for various tracking purposes. Real time scenarios where cookies can be used include, user session management, remembering username and password, tracking the number of times an user visited the site and so on. Cookies in most cases are considered a serious security threat, because storing user information in client's browser may lead to misuse of it by other users of the machine. But still, cookies can never be interpreted, so it cannot be used to insert viruses and attack client machine. Also, browsers limit the total number of cookies a browser can store, the maximum number of cookies a browser can receive from any site and the maximum size for each cookie. Therefore, cookies cannot be used to fill up client machine's disk space.

In this post, let us have a look at how cookies can be created and used to display user specific content using jQuery Cookie Plugin. jQuery Cookie plugin is a simple lightweight jQuery plugin that helps you to read, write and delete cookies. Download jQuery Cookie plugin from here

In the below example, I am going to determine whether the visitor is a first time visitor or a returning visitor and display content accordingly. First, let us create an html file where the user enters username and password to login. Create a text file and save it as login.html. Place the "jquery.cookie.js" file you downloaded in the same folder where you have created this html file. Copy paste the below content.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>jQuery Cookie Sample</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("#form1").submit(function() {
     //Check whether the cookie is already set
     var cookiename='visitcount';
       //$.cookie('visitcount',null,{path:'/'});
     if($.cookie(cookiename))
     {
      //set visitcount cookie with incremented cookie value
      $.cookie('visitcount',(parseInt($.cookie('visitcount')) + 1),{expires:1,path:'/'});
     } 
     else
      { 
      //set visitcount to 1 for first if the cookie is not already set
      $.cookie('visitcount',1,{expires:1,path:'/'});
      }
});
});
</script>
</head>
<body>
<form id="form1" name="form1" action="promotion.html">
<h1>Login</h1>
Username:<input type="text" id="username"/>
Password:<input type="password" id="password"/>
 <input type="submit" id="login" value="Login"/>
</form>

</body>
</html>

Now create another html file in the same location and name it as 'promotion.html'. Copy and paste the below content.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="jquery.cookie.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
     //get cookie value
       var count = parseInt($.cookie('visitcount'));
     //if the value of cookie is greater than 1
     //show content for repeating user
        if (count > 1) {
         $('.repeatinguser').show();
            $('.newuser').hide();         
        }
     //if the value of cookie is equal to 1
     //show content for new user
        else if(count==1){
         $('.newuser').show();
         $('.repeatinguser').hide();
        } 
    });
</script>
</head>
<body>
<div class="newuser" style="display:none;">
<h2>Welcome to our shopping site!!</h2>
<p>You can avail 10% off on all our products as first time offer!</p>
</div>
<div class="repeatinguser" style="display:none;">
<h2>Welcome to our shopping site!!</h2>
<p> Thank you for visiting our site once again</p>
</div>
</body>
</html>


Now open the login.html file in a browser, and fill username and password with dummy values and click on login button. 


Setting and Getting Cookies using jQuery Cookie plugin

When you click on login button after entering the username and password you will be redirected to 'promotion.html' page, where you will see the content for a new user (content inside 'newuser' div) getting displayed as shown below. Whenever an user submits login.html page, the jquery script checks whether a cookie in the name 'visitcount' exists in the browser, and increments the value of 'visitcount' cookie if it exists or sets the value to 1 indicating first time visit.


Setting and Getting Cookies using jQuery Cookie plugin


Now close the browser window and open login.html file again, this time you will see the content for returning users as shown below since the cookie value no more equals to 1.


Setting and Getting Cookies using jQuery Cookie plugin

Setting a Cookie

To set a cookie, use the cookie() method, passing cookie name and value as arguments.

$.cookie('the_cookie', 'the_value');

This is a session cookie and will be destroyed whenever an user exits the browser.

To set a persistent cookie, that is to keep the cookie active for a specific time period, use expires option as shown below,
$.cookie('the_cookie', 'the_value',{expires:30});

This will keep the cookie alive for 30 days.

To set the cookie valid for the entire site, use the path option as shown below


$.cookie('the_cookie', 'the_value',{expires:30,path:'/'});

This will keep the cookie alive for 30 days and will be valid across all the url's of the site. If you do not specify the path option, by default the path of the cookie is the path of the page where the cookie was created.

Reading a Cookie

To read an existing cookie,

$.cookie('the_cookie');

This will return the value of the cookie if it exists, otherwise returns null.

Deleting a Cookie

To delete an existing cookie,

$.cookie('the_cookie',null,{path:'/');

This will delete the existing cookie. When deleting a cookie you must pass the same exact path, domain and other secure options that were used to set the cookie.


Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts.Thanks for reading!!


Subscribe to GET LATEST ARTICLES!


Related

Jquery 2966914025860840092

Post a Comment

emo-but-icon

SUBSCRIBE


item