weichan8t1
weichan8t1

Reputation: 51

How to set multiple values in a single cookie using a delimiter?

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>

Upvotes: 5

Views: 15645

Answers (3)

Alf Tau
Alf Tau

Reputation: 21

Well, as to delimiters mentioned by Sven L. You've got Joe%7C31%7CAthlete because

  • %7C is an url encoded value for char vertical bar "|"

As to other separators mentioned, please see Allowed characters in cookies.

As for me in firefox, '-' and '.' were stored unencoded in single byte but '+' was converted to its encoded value %2B

It makes sense to choose separators that won't be encoded. This way the separator will only take 1 byte. So, one can put more useful stuff into cookie value taking into account its size limit of 4kB.

Upvotes: 2

svenlr
svenlr

Reputation: 86


don't use '|' as a delimiter, its implemented differently in different browsers (use such things as '-', '+', '.' etc for your delimiter). when i check firefox > site information, it tells me that there is a cookie, but that the content is Joe%7C31%7CAthlete. in my version, i put the delimiter in a variable that we define before everything (i took '---', but you can change it if you want):

 <!DOCTYPE html>
<html>
<head>
<title> Using a delimiter to save on cookies used</title>


<script>
var delimiter = "---";

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 whole_cookie=document.cookie.split(nameEquals)[1].split(";")[0]; // get only the value of the cookie we need 
                                                                         // (split by the name=, take everything after the name= and then split it by ";" and take everything before the ";")
    var crumbs=whole_cookie.split(delimiter); // split now our cookie in its information parts
    /*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));
        }
    }*/ // sorry... i dont understand what this does ;) but it works without it
    return crumbs; // return the information parts as an array
}

function deleteCookie(name){
    createCookie(name, "", -1);
}

// ---------------------
// DEBUGGING PART STARTS
// ---------------------

var userdata="Joe"+delimiter+"31"+delimiter+"Athlete";

createCookie("user", userdata);

var myUserArray=getCookie("user");

var name=myUserArray[0];

var age=myUserArray[1];

var profession=myUserArray[2];

alert(myUserArray[0]);
alert(myUserArray[1]);
alert(myUserArray[2]);

// ---------------------
// DEBUGGING PART ENDS
// ---------------------
</script>
</head>

<body>

</body>

</html>

when i test this, it works correctly: it saves "Joe" in name, "31" in age and "Athlete" in job
i added some alert for debugging so that you can test it too
bye, i hope i could help :)

Upvotes: 3

zeroos
zeroos

Reputation: 2204

For me your code works perfectly on Chrome.

However, I have had to run it on a web server - if I just open a html file it does not save any cookies.

If you have python installed on your machine you can run a minimalistic python server with this command from the directory with html files you want to serve:

$ python -m SimpleHTTPServer 8000

Then, just go to http://127.0.0.1:8000 with your browser and the Web site should work.

Of course you can also use any other http server, like apache or whatever you'd like.

Upvotes: 0

Related Questions