st4cker
st4cker

Reputation: 73

Setting and retrieving cookies in javascript

So i am learning Javascript and trying to set and retrieve a cookie, my code all looks to be ok but there is obviously a problem here.

function init()
{
    var panel = document.getElementById("panel");

    var user = escape("Dan, 000456");
    var expiry = new Date();
    expiry.setTime(expiry.getTime() + (7*24*60*1000) );
    document.cookie = "myData=" + user + ";" + "expires=" + expiry.toGMTString() + ";";

    if (document.cookie)
    {
        var cookieString = unescape(document.cookie);
        var list = cookieString.split("=");
        if (list[0] === "myData")
        {
            var data = list[1].split(",");
            var userName = data[0];
            var userAcct = data[1];
        }
    }

    panel.innerHTML += "Cookie String:" + cookieString;
    panel.innerHTML += "<br>Split List:" + list;
    panel.innerHTML += "<br>User Name:" + userName;
    panel.innerHTML += "<br>User Account:" + userAcct;
}
document.addEventListener("DOMContentLoaded",init, false);

When I look in the results they are not what I am expecting to see:

Cookie String:undefined
Split List:undefined
User Name:undefined
User Account:undefined

Upvotes: 0

Views: 149

Answers (1)

Larry Lane
Larry Lane

Reputation: 2191

Your main issue is now that you have corrected your syntax errors is that the following line:

var user = escape("Dan, 000456");

note: I believe the escape function is now deprecated?

change your javascript to this and make sure your browser allows cookies:

    function init(){

    var panel = document.getElementById("panel");

    var user = ["Dan, 000456"];  //<--change #1
    var expiry = new Date();
    expiry.setTime(expiry.getTime() + (7*24*60*1000) );

    //change #2 below added the array index of user to set the cookie value for myData
    document.cookie = "myData=" + user[0] + ";" + "expires=" + expiry.toGMTString();



    if (document.cookie)
    {
        var cookieString = unescape(document.cookie);
        var list = cookieString.split("=");
        if (list[0] === "myData")
        {
            var data = list[1].split(",");
            var userName = data[0];
            var userAcct = data[1];
        }
    }

    panel.innerHTML += "Cookie String:" + cookieString;
    panel.innerHTML += "<br>Split List:" + list;
    panel.innerHTML += "<br>User Name:" + userName;
    panel.innerHTML += "<br>User Account:" + userAcct;
           }
document.addEventListener("DOMContentLoaded",init, false);

Also make sure your html looks like this:

<div id="panel">Test</div>

You can remove the Test from the div in the html above if you want. The Test value should be replaced by values in your panel.innerHTML assignments.

Upvotes: 1

Related Questions