CIT041J Index > Lecture Notes - Cookies

CIT041J Lecture Notes - Cookies

HTTP is Stateless

No, this doesn’t mean that HTTP isn’t a citizen of any country. It means that every request for a web page is an independent transaction. Servers don’t remember who requested what when. Ordinarily, this is no problem. If Joe Doakes requests page1.html and then Bertha Bupkis requests that same page ten seconds later, does the server really care? Once you start filling in forms that require you to remember information, though, the statelessness of HTTP is a pain.

Consider this first page of a form, where Joe Doakes enters his name:

Your name:

On the next page, we would like to personalize the response. (Even if we didn’t want to personalize it, we would still want to know that this is Joe’s purchase, and not Bertha’s!)

Thanks, Joe Doakes! How many frammistats do you want to buy?

In short, the server must somehow keep track of information from one page to another. There are lots of ways to do this, but the one we will explore (because it works well with JavaScript) is cookies.

Cookie Format

You set a cookie with statements like this:

document.cookie = "cookieName=cookieData"; // generic form
document.cookie = "userName=Joe";

document.cookie = "item=toner;" +
   "expires=Mon, 04 Jan 2016 05:03:05 GMT";
document.cookie = "price=34.95;" +
   "expires=Mon, 04 Jan 2016 05:03:05 GMT";

If you set an expiration date (which must be in the form of Greenwich Mean Time), the cookie stays around until that time. If you don’t set an expiration date, the cookie vanishes as soon as you exit the browser.

The cookie data cannot contain any commas, semicolons, or whitespace. In order to accommodate data that does contain these characters, we will URL-encode the data. That is, we will use the built-in escape() function to encode the data in a form that contains only characters that are allowed in a URL. The button below will call a function that sets a cookie with the value in the form.

Please enter your name:

<form name="theForm" action="#">
Please enter your name:<input type="text" name="yourName" />
<input type="button" value="Set Cookie" onClick="setCookie();">
</form>

function setCookie()
{
    var response = document.theForm.yourName.value;
    if (response == "")
    {
        response = "Mystery Guest";
    }
    document.cookie = "yourName=" + escape(response);
}

Proceed to next page, please.