I have been utilizing JavaScript to set and retrieve cookie values. The code I am using can be found at http://www.w3schools.com/js/js_cookies.asp. Upon page load, I check if the cookie exists or not. Everything is functioning properly except for the issue where it fails to read the cookie when initially setting it and attempting to read it on the next page load. Although the cookie gets set, it only fails to read on the first attempt.
Below is the code snippet I have implemented:
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);
}
On page load, my implementation looks like this:
$(document).ready(function () {
var aZ = getCookie("menuSave");
if (aZ) {
//do Something here
}
else {
setCookie("menuSave", "mysp", null);
}
});