[How to] Set and get/read cookie with JavaScript

Started by Xhanch Studio, May 19, 2011, 12:13:12 PM

previous topic - next topic
Go Down

Xhanch Studio

May 19, 2011, 12:13:12 PM Last Edit: May 19, 2011, 12:21:17 PM by Xhanch Studio
Cookies can be created, read and erased by JavaScript. They are accessible through the property document.cookie. Though you can treat document.cookie as if it's a string, it isn't really, and you have only access to the name-value pairs.

Here are two JavaScript functions to set and get cookie:
Code Select
function set_cookie(name, val, exp, pth, dmn, sec){
var tdy = new Date();
tdy.setTime(tdy.getTime());
if(exp)
exp = exp * 1000 * 60 * 60 * 24;
var dte_exp = new Date(tdy.getTime() + exp);

document.cookie = name + "=" + escape(val) +
(exp?";expire=" + dte_exp.toGMTString():"") +
(pth?";path=" + pth:"") +
(dmn?";domain=" + dmn:"") +
(sec?";secure":"");
}

function get_cookie(chk_nme) {
var lst_cke = document.cookie.split(";");
var tmp_cke = '';
var cke_nme = '';
var cke_val = '';
var cke_fnd = false;

for(var rpi=0;rpi<lst_cke.length;rpi++){
tmp_cke = lst_cke[rpi].split("=");
cke_nme = tmp_cke[0].replace(/^\s+|\s+$/g, "");
if(cke_nme == chk_nme ){
cke_fnd = true;
if(tmp_cke.length > 1)
cke_val = unescape(tmp_cke[1].replace(/^\s+|\s+$/g, ""));
return cke_val;
break;
}
tmp_cke = null;
cke_nme = "";
}

if(!cke_fnd)
return null;
}
Best Regards,
Susanto B.Sc
----------------------------------------------------------------------------
Web development services, WordPress plugin and theme development, PSD to XHTML conversion - http://xhanch.com
Read free manga online - http://authrone.com

Go Up