1

Possible Duplicate:
What is the “best” way to get and set a single cookie value using JavaScript
Read cookies with JavaScript

When I print_r( $_COOKIE ); in php, I am getting following result.

Array ( [filters] => Array ( [cat] => 1 ) ) 

Now I want to get value of cat from cookies using JavaScript.

I have tried this:

 function getCookies() {

      var pairs = document.cookie.split(";");
      var cookies = {};
      for (var i=0; i<pairs.length; i++){
        var pair = pairs[i].split("=");
        cookies[pair[0]] = unescape(pair[1]);
      }
      return cookies;
}

When I alert returned result from above function then I am getting an [object Object]. But I don't know how to get value of cat from that object.

How to know value of cat from that returned object ?

Thanks

Community
  • 1
  • 1
Student
  • 1,863
  • 9
  • 37
  • 50
  • @Widor: I have read but I want to go deep in cookies array. I have tried it but getting `undefined`. – Student Nov 02 '11 at 13:30
  • @Student that is an entirely different question. If you're trying to figure out why your code doesn't work, don't ask "how do I do `X`?" Ask a question **about your code.** – Matt Ball Nov 02 '11 at 13:31
  • Don't be so quick to close a question without pointing out errors in my question and without giving me time to explain my question using **Edit** option.. – Student Nov 02 '11 at 13:37

2 Answers2

3

document.cookie. You might also like to read Quirksmode – Cookies.


Edit re OP edit:

When I alert returned result from above function then I am getting an [object Object]. But I don't know how to get value of cat from that object.

How to know value of cat from that returned object ?

The problem is that alert() sucks for debugging. Anything you pass to alert is converted to a string, but objects don't have a terribly useful toString() method. Use a real debugger (and console.log() instead of alert()) instead.

See How can I debug my JavaScript code?

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

I believe a Google search would serve you better than a SO post. With that being said, the code below is one of dozens of examples that appears when I Googled "javascript get cookie".

function getCookie(name) {
    var dc = document.cookie;
    var begin = dc.indexOf(name);
    var end = (dc.indexOf(";", begin) == -1) ? dc.length : dc.indexOf(";", begin);

    return unescape(dc.substring((begin + (name.length + 1)), end));
}
Widor
  • 13,003
  • 7
  • 42
  • 64
James Hill
  • 60,353
  • 20
  • 145
  • 161