Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if cookie exists not working

I'm using the below code to check if a cookie exists with a certain value then do something.

$(document).ready(function() {
   if (document.cookie.indexOf('samplename=itsvalue')== -1 ) {
      alert("cookie");
   }
});

It always displays the alert whether the cookie exists or not. What I'm doing wrong here?

like image 785
Mina Hafzalla Avatar asked Oct 18 '15 20:10

Mina Hafzalla


1 Answers

Original response:

Unless you have a cookie with the key "samplename=itsvalue", your code will always evaluate to true. If the key is "samplename" and the value is "itsvalue", you should rewrite the check like this:

if (document.cookie.indexOf('samplename') == -1 ) {
  alert("cookie");
}

This will tell you that the cookie does not exist.

To see if it does exist:

if (document.cookie.indexOf('samplename') > -1 ) {
  alert("cookie exists");
}

Updating to better address this question:

What you are looking for in that check will always evaluate to true and throw the alert. Add the following function to your js and call it to check if your cookie exists.

function getCookie(name) {
    var cookie = document.cookie;
    var prefix = name + "=";
    var begin = cookie.indexOf("; " + prefix);
    if (begin == -1) {
        begin = cookie.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
        end = cookie.length;
        }
    }
    return unescape(cookie.substring(begin + prefix.length, end));
} 

You can then check your cookies with the following:

var myCookie = getCookie("samplename");

if (myCookie == null) {
    alert("cookie does not exist");
} else {
    alert("cookie exists");
}
like image 82
buzzsaw Avatar answered Nov 06 '22 04:11

buzzsaw