Below is the example that I am trying to figure out why it doesn't work exactly.
It keeps giving me null values.
I am trying to learn how to set multiple values in a single cookie.
Each cookie contains one name=value pair, so if you need to store several separate pieces of data such as user's name, age, and membership number, you need three different cookies.
Instead of doing that, I'm using a delimiter technique to split it so I can use fewer cookies.
Please show me any examples of this correctly implemented if you can. I've seen some material for other programming languages but I would like to know how it is done in JavaScript specifically.
<!DOCTYPE html>
<html>
<head>
<title> Using a delimiter to save on cookies used</title>
<script>
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date=new Date();
date.setTime(date.getTime()+ (days*24*60*60*1000));
var expires=date.toGMTString();
}
else var expires = "";
cookieString= name + "=" + escape (value);
if (expires)
cookieString += "; expires=" + expires;
if (path)
cookieString += "; path=" + escape (path);
if (domain)
cookieString += "; domain=" + escape (domain);
if (secure)
cookieString += "; secure";
document.cookie=cookieString;
}
function getCookie(name) {
var nameEquals = name + "=";
var crumbs=document.cookie.split('|');
for (var i = 0; i<crumbs.length; i++) {
var crumb = crumbs [i];
if (crumb.indexOf(nameEquals) == 0) {
return unescape (crumb.substring(nameEquals.length, crumb.length));
}
}
return null;
}
function deleteCookie(name){
createCookie(name, "", -1);
}
var userdata="Joe|31|Athlete";
createCookie("user", userdata);
var myUser=getCookie("user");
var myUserArray=myUser.split('|');
var name=myUserArray[0];
var age=myUserArray[1];
var profession=myUserArray[2];
</script>
</head>
<body>
</body>
</html>