Sunday 7 July 2013

Use JavaScript Cookies

How to create javascript cookies, get and delete cookies, just follow below code.

if you are using SESSION in php and you want to use this session in JavaScript then it will be not possible session php to JavaScript. so here you can use cookie in JavaScript.


Create cookies
 
function setCookie(c_name,value,exdays){
 var exdate=new Date();
 exdate.setDate(exdate.getDate() + exdays);
 var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
 document.cookie=c_name + "=" + c_value;
}

Here c_name is cookie name, value is nothing but value which you want to stored in cookie name and exdays is time period after this time cookie will delete.
 
Get cookies
 
function getCookie(c_name){
 var c_value = document.cookie;
 var c_start = c_value.indexOf(" " + c_name + "=");
 if (c_start == -1){
    c_start = c_value.indexOf(c_name + "=");
  }
 if (c_start == -1){
    c_value = null;
 }else{
    c_start = c_value.indexOf("=", c_start) + 1;
    var c_end = c_value.indexOf(";", c_start);
    if (c_end == -1){
   c_end = c_value.length;
    }
    c_value = unescape(c_value.substring(c_start,c_end));
 }
 return c_value;
}

Delete cookies

function delete_cookie(name){
    document.cookie = name+'=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

Here name is cookie name which you want to delete.
Now you can use these cookie very easily let see,

Set cookie 
setCookie("name_of_cookie",value_of cookie,1);
 
1 is time period after this time this cookie will delete automatically.  

Get cookie 
to retrieve the cookie
 
var price = getCookie("name_of_cookie");
 
Delete cookie
delete_cookie("name_of_cookie");

No comments: