Pranav Pranav - 11 months ago 88
ASP.NET (C#) Question

unable to read cookie first time in javascript

I am using Javascript to set the cookie and read the value from cookie.I am using the code available at for creating and reading the value of cookie.when the page loads i am checking that whether that cookie exists or not .Every thing is working fine except it is not reading the cookie when i set it first time and try to read in next page load .it is setting the cookie but does not read only first time .

Here is my code :-

function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;

//To get the cookie:-
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
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);
//to Delete the cookie:-
function cookieDelete(c_name) {
setCookie(c_name, "delete", -1);

And on page load i am using it like :-

$(document).ready(function () {

var aZ = getCookie("menuSave");
if (aZ) {
//do Some thing here
else {
setCookie("menuSave", "mysp", null);



Answer Source

You need to add a 'path' to your cookie. For example:

document.cookie = 'ppkcookie2=yet another test; expires=Fri, 27 Jul 2001 02:47:11 UTC; path=/';

The path represents the relative path in your website which the cookie will be readable.

path=/ means it'll be readable on your whole website.
path=/common/ means it'll be readable only in /common/ folder (and its subfolders)