0

I'm trying to get exist cookie with the following code:

  function readCookie(name) {

    var nameEQ = name + "=";
    var ca = document.cookie.split(';');

    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        console.log(c);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

I have the cookie name but i'm always getting NULL.

I see the cookie at the developer tool (https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies)

but document.cookie is ""

CSharpBeginner
  • 601
  • 2
  • 7
  • 22
  • *"I need to change some configuration at the server side?"* I thought I understood your question, but now I don't. You want to use client-side javascript to change something on the server? – ʰᵈˑ Mar 01 '17 at 15:26
  • No, I'm just want to get the cookie – CSharpBeginner Mar 01 '17 at 15:27
  • Possible duplicate of [Set cookie and get cookie with JavaScript](http://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript) – ʰᵈˑ Mar 01 '17 at 15:29
  • Are you sure that the cookie exists and includes `name`? [Check with your browser debugger.](https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies) – Blazemonger Mar 01 '17 at 15:29
  • Possible duplicate of [How do I create and read a value from cookie?](http://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie) – evolutionxbox Mar 01 '17 at 15:35
  • Your function works on my cookies. – Shilly Mar 01 '17 at 15:38
  • @Blazemonger, Yeah i'm sure the cookie is exists but i cant get the cookie – CSharpBeginner Mar 01 '17 at 15:43

1 Answers1

0

try this

function readCookie(name){
    var nameEQ = name+"=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        if (c.indexOf(nameEQ) !=-1) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
document.cookie="name=sagar;expire=";
console.log(readCookie(`name`));
Sagar V
  • 12,158
  • 7
  • 41
  • 68