Recent Posts

Friday 15 May 2015

Dealing with cookies using javascript


Hello guys, I am designing a website for project NEWSONSPOT, there i am going to use the cookies. I planned to write two default functions to set the cookies and get the cookies.

Here is the two functions setCookie and readCookie.
 
Assuming you know the basics of JavaScript.Place the below two functions in the js file and link that file in your html file to use the functions .

//getting the cookies in the form of string
var cok=document.cookie;


//function for reading the cookie value
function readCookie(str){ var cokee=cok.split(";");var coki;
var index=cok.indexOf(str);
for(coki=0;coki<cokee.length;coki++) {
 if(coke[coki].indexOf(str)!=-1 && cok[index-2]==";")
   { var len=cokee[coki].length;
   var eq=cokee[coki].indexOf("=");
   return cokee[coki].substr(eq+1,len);
   }
   }
   return null;
}


//function for setting the cookie value valid upto 1 hour and path is "/"
function setCookie(cname,cvalue){ var d=new Date(); d.setTime(d.getTime()+1000*60*60);
    document.cookie=cname+"="+cvalue+";expires="+d.toUTCString()+";path=/";
}

//function for deleting the cookie
function delCookie(name){ document.cookie=name+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/"; }


Smart Siva

Author & Editor

In Life every second is important, In programming every line of code is important.

0 comments:

Post a Comment

 
biz.