Wednesday, July 10, 2013

Implement "Remember Me" option for login using Javascript(JQuery) cookies

1. Get JQuery Cookie library in hand

To implement this first you need to have JQuery Cookie library. So please save following JS file as "jquery.cookie.js", or you can directly download from Github .

//Save it as jquery.cookie.js
/*!
 * jQuery Cookie Plugin v1.3.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
 if (typeof define === 'function' && define.amd) {
  // AMD. Register as anonymous module.
  define(['jquery'], factory);
 } else {
  // Browser globals.
  factory(jQuery);
 }
}(function ($) {

 var pluses = /\+/g;

 function raw(s) {
  return s;
 }

 function decoded(s) {
  return decodeURIComponent(s.replace(pluses, ' '));
 }

 function converted(s) {
  if (s.indexOf('"') === 0) {
   // This is a quoted cookie as according to RFC2068, unescape
   s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
  }
  try {
   return config.json ? JSON.parse(s) : s;
  } catch(er) {}
 }

 var config = $.cookie = function (key, value, options) {

  // write
  if (value !== undefined) {
   options = $.extend({}, config.defaults, options);

   if (typeof options.expires === 'number') {
    var days = options.expires, t = options.expires = new Date();
    t.setDate(t.getDate() + days);
   }

   value = config.json ? JSON.stringify(value) : String(value);

   return (document.cookie = [
    config.raw ? key : encodeURIComponent(key),
    '=',
    config.raw ? value : encodeURIComponent(value),
    options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
    options.path    ? '; path=' + options.path : '',
    options.domain  ? '; domain=' + options.domain : '',
    options.secure  ? '; secure' : ''
   ].join(''));
  }

  // read
  var decode = config.raw ? raw : decoded;
  var cookies = document.cookie.split('; ');
  var result = key ? undefined : {};
  for (var i = 0, l = cookies.length; i < l; i++) {
   var parts = cookies[i].split('=');
   var name = decode(parts.shift());
   var cookie = decode(parts.join('='));

   if (key && key === name) {
    result = converted(cookie);
    break;
   }

   if (!key) {
    result[name] = converted(cookie);
   }
  }

  return result;
 };

 config.defaults = {};

 $.removeCookie = function (key, options) {
  if ($.cookie(key) !== undefined) {
   // Must not alter options, thus extending a fresh object...
   $.cookie(key, '', $.extend({}, options, { expires: -1 }));
   return true;
  }
  return false;
 };

}));



2. Add "Remember Me" check box on Login page

Add "Remember Me" check box in login form, then include "jquery.cookie.js" and your JS file (here: login.js).

<input type="text" id="username" /><br />
<input type="password" id="password" /><br />
<input type="checkbox" id="c1" />Remember Me<br />
<input type="submit" id="loginsubmit" />
.
.
.
<script src="js/jquery.cookie.js"></script>
<script src="js/login.js"></script>


3. Set and Get Cookie using JQuery

Now, set entered username on cookie, or display username if already avail on cookie. To do this,
include following line in your JS file (here: login.js)

$(document).ready(function()
{

// Please read these set of code after you read next set. So that you can understand simply.
var username=$.cookie("username");   // Get username from cookie on form load.
if(username!=undefined)
{
$('#loginsubmit').val(username);   // Display username on input box if avail on cookie.
      $('#c1').prop('checked', true);  // Check check box manually by us. So that duration for current email will reset.
}

// Read this set first.
$('#loginsubmit').click(function()
{
      if($('#c1').is(':checked')) // If user checked remember me check box
{
                var email=$('#loginsubmit').val(); // Get entered username or email
                //  Set username on cookie when login form submit.
$.cookie("username", email, { expires: 365 });  // Remember username for 1 year.
}
      // Your other codes...
}

});


Note:
1. Assign username or email to cookie after you done form validation like email validation, empty checking, so that you can sure for stored value are original.

2. And here we set username or email on cookie for one year. You don't need to worry about like "will expire after one year?". Because it will reset to one year whenever user try to login. And only go empty once if the user not login even one time for a year. You can change this duration as you need.

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...