Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve jQuery Cookie value

Example, I have this cookie:

$.cookie("foo", "500", { path: '/', expires: 365 });

How do I get the value of that cookie and put it into a variable?

For example (I know this is not correct):

var foo = $.cookie("foo").val();
like image 480
daryl Avatar asked May 30 '11 02:05

daryl


People also ask

How do I get the value of a cookie?

Function explained: Loop through the ca array (i = 0; i < ca.length; i++), and read out each value c = ca[i]). If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length, c.length). If the cookie is not found, return "".

How can you access a cookie from JavaScript?

In JavaScript, we can create, read, update and delete a cookie by using document. cookie property.

How do you use cookie values?

Domain: Specifies the domain name of the website. Name=Value: Cookies are stored in the form of name-value pairs. Path: Specifies the webpage or directory that sets the cookie. Secure: Specifies whether the cookie can be retrieved by any server (secure or non-secure).


4 Answers

It's just var foo = $.cookie("foo").

There's no need for a .val() call as you're not accessing the value of a DOM element.

like image 94
Matt Ball Avatar answered Sep 20 '22 13:09

Matt Ball


This worked for me

function getCookieValue(cname) { // cname is nothing but the cookie value which 
                                 //contains the value
                    var name = cname + "=";
                      var decodedCookie = decodeURIComponent(document.cookie);
                      var ca = decodedCookie.split(';');
                      for(var i = 0; i <ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0) == ' ') {
                          c = c.substring(1);
                        }
                        if (c.indexOf(name) == 0) {
                          return c.substring(name.length, c.length);
                        }
                      }
                      return "";
                    }
like image 30
Ankit Singh Avatar answered Sep 17 '22 13:09

Ankit Singh


To get the value of a cookie, you can just call it's reference. For example:

$.cookie("foo", "somevalue");
alert($.cookie("foo"));

Will alert:

somevalue
like image 31
Sean Powell Avatar answered Sep 20 '22 13:09

Sean Powell


By this way we can access

console.log($.cookie()); //It will gives the all cookies in the form of object

alert($.cookie('foo'));//it will give cookie foo value ie 500

like image 34
Mahendra Jella Avatar answered Sep 18 '22 13:09

Mahendra Jella