It works fine for me but Once again Make sure if your JS
and Cookies
are enabled in browser. Your should check whether you cookie is setting properly or not using if(document.cookie)
, it will then be easier for you debugging where the problem is. Maybe you're cookies are not written properly. Please do consider the following code.
Write the Cookie
Use the following code to write your cookie:
<script language="JavaScript">
cookie_name = "Basic_Cookie";
function write_cookie() {
if(document.cookie) {
index = document.cookie.indexOf(cookie_name);
} else {
index = -1;
}
if (index == -1) {
document.cookie=cookie_name+"=1; expires=Wednesday, 01-Aug-2040 08:00:00 GMT";
} else {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == -1) {
countend = document.cookie.length;
}
count = eval(document.cookie.substring(countbegin, countend)) + 1;
document.cookie=cookie_name+"="+count+"; expires=Wednesday, 01-Aug-2040 08:00:00 GMT";
}
}
</script>
Read Your Cookie
Once you've written the cookie, you need to read it in order to use it. Use this script to read your cookie:
<script language="JavaScript">
function gettimes() {
if(document.cookie) {
index = document.cookie.indexOf(cookie_name);
if (index != -1) {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == -1) {
countend = document.cookie.length;
}
count = document.cookie.substring(countbegin, countend);
if (count == 1) {
return (count+" time");
} else {
return (count+" times");
}
}
}
return ("0 times");
}
</script>
Call Your Cookie in a Link
Set your cookie when someone clicks a link with this code in your HTML body:
<script language="javascript">document.write(gettimes());</script>
Reference: Simple Cookie Read & Write
Hope this helps.