Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing cookies in javascript [duplicate]

Possible Duplicate:
Read cookie in javascript

I have written the following function. I need to access cookies using the format $COOKIE['cookieName'].

var $COOKIE = (function(){
    if(!document.cookie)
        return {};
    else{
        var c = document.cookie.split(';');
        var len = c.length;

        var ret = {};
        var temp ;

        for( var i = 0 ; i < len ; ++i )
        {
            temp = c[i].split('=');

            ret[temp[0]] = temp[1];
        }

        return ret;
    }
})();

I have set two cookies a1= 2 , a2 = 9. $COOKIE['a1'] gives me 2, but $COOKIE['a2'] is undefined.

Why is it happening? What is the problem in my logic/code?

like image 586
Jinu Joseph Daniel Avatar asked Aug 07 '26 09:08

Jinu Joseph Daniel


2 Answers

The Problem is that you're splitting by ";" but the values in a cookie are separated by "; " (semicolon + whitespace). Thus your second value would be " a2": 9

To fix it, simply add a whitespace to the delimiter or use this snippet for a more data-centric approach ;)

var $COOKIE = (document.cookie || '').split(/;\s*/).reduce(function(re, c) {
  var tmp = c.match(/([^=]+)=(.*)/);
  if (tmp) re[tmp[1]] = unescape(tmp[2]);
  return re;
}, {});
like image 114
Tharabas Avatar answered Aug 09 '26 21:08

Tharabas


Try this

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i += 1) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x === c_name) {
            return (unescape(y));
        }
    }
}
like image 24
Downpour046 Avatar answered Aug 09 '26 23:08

Downpour046



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!