Happy New Year

Javascript and cookies

Cookies are small strings of data that are stored directly in the browser. They are a part of HTTP protocol. Cookies are usually set by a web-server using response Set-Cookie HTTP-header. Then the browser automatically adds them to (almost) every request to the same domain using Cookie HTTP-header.

Example Set Cookie

function set_Cookie(cvalue) {
  var d = new Date();
  d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toUTCString();
  document.cookie = "c_sharphub" + "=" + cvalue + ";" + expires + ";path=/";
}

//set cookie value
set_Cookie("bilalchaudhari");

Example Get Cookie

function get_Cookie() {
  var name = "c_sharphub" + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i < ca.length; i++) {
  var c = ca[i];
  while (c.charAt(0) == ' ') {
  c = c.substring(1);
}
if (c.indexOf(name) == 0) {
  return c.substring(name.length, c.length);
}
}
   return "";
}

//get cookie value
var data = get_Cookie();

Example Remove Cookie

function remove_Cookie() {
  var name = "c_sharphub";
  document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;";
  document.cookie = "c_sharphub=; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";
}

//Remove cookie value
remove_Cookie();