My professor says I have a logic error in the greetUser function of code I was already graded on. The code is based on the example in the text, so I’m stunned as to determining the logic. This was her message to me:
The
greetUserfunction is not reading the cookie correctly for the returning visitor.
Check this line of code in thereadCookiefunction – it has a logic error.
This is the readCookie function:
function readCookie(name) {
var nameEQ = name + "=";
var x = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = cookies[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
This is the greetUser function:
function greetUser(){
userName = readCookie("rock_username");
if(userName)
alert("Hello " + userName + ", I missed you.");
else
alert("Hello, I am your pet rock");
}
From my novice eyes it all looks logical to me, the same as it was in the text example.
Any suggestions
You are iterating on “ca” (what is that?) instead of “x”, and then you are reading from the
cookiesarray? 3 different variables, same meaning?I’ll explain:
var x = document.cookie.split(';');splits the string stored indocument.cookieinto an array, that will effectively be held inside thexparameter.Then, inside the
for()construct, you are increasingiup until the amount of elements found inside the array you just created from splitting the string. That way, each time you doc = x[i]; (correct version) you will get the next portion of thedocument.cookiestring that you split with the ‘;’ character.This allows you to work on all the interesting parts of
document.cookie, which are, by definition, the user agent (browser) cookies. In your example, you are iterating over the cookies to find a specific one – the ‘name’ cookie – in order to print it as a greet to the user.Good luck!