Nothing
Nothing

Reputation: 2642

Cannot access cookie in javascript

I created a function to get the cookie in javascript :

   function getCookie() {
        var arr = document.cookie.split(";");
        for (i = 0; i < arr.length; i++) {
            if (arr[i].substr(0, arr[i].indexOf("=")).replace(/^\s+|\s+$/g, "") == "taxibleC") {
                return arr[i].substr(arr[i].indexOf("=") + 1);
            }
        }
    }
    var multipleVAT = 1;

And then I have another function to initialize the cookie :

  function ChangeVATValue() 
   {
      if ($("#vatEnable").is(':checked')) {
         multipleVAT = 1;
      } else {
         multipleVAT = 0;
      }
      document.cookie = "taxibleC=" + multipleVAT;
      alert(getCookie());
   }

When I used alert(getCookie());, It has the value 1. But when I click to another page, the alert is 0.

Could anyone tell me, why I cannot access the session by using the getCookie() method in the view of my asp.net MVC 3.0 project.

Upvotes: 0

Views: 212

Answers (2)

Pranay Rana
Pranay Rana

Reputation: 176886

That is because you cookie might get expire immediatly, if possible se cookie expiration time to certail limit and than access the value of cookie on another page that resolve your issue

something like

document.cookie =
  'ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'

Upvotes: 2

Muthu Kumaran
Muthu Kumaran

Reputation: 17900

You need to set path in the cookie for accessing in different page

;path=/

For example,

document.cookie = 'YOUR COOKIE DATA;path=/'

Upvotes: 1

Related Questions