Setting Cookies

Exercise

We will set a cookie on one page that records a name and then reads that name from another page.

Cookie Demonstration

Bake a cookie

To set a basic cookie you create a string in the form of
cookie_name= variable:value

Here we are setting the cookie's name to a variable name and its value.

We then set the document's cookie property, document.cookie to that string.

We are going to save the cookie with the name mycookie to the hard drive and with the value username:fred%20derf
This cookie will store your name as a cookie.

Here is a javascript function to set the cookie

function setCookie(){
var your_name = prompt("What's your name?","");
var the_cookie = "mycookie=username:" + escape(your_name);
document.cookie = the_cookie;
alert("Thanks, now go to the next page.");
}

The prompt allows the user to enter their name and stores it in a variable called your_name

The middle two lines of this function are the critical ones:

var the_cookie = "mycookie=username:" + escape(your_name);
document.cookie = the_cookie;

If I entered "fred derf" at the prompt, the first line would create a string that looks like
mycookie=username:fred%20derf.

This means that I'm going to save a cookie named mycookie to the hard drive.
That cookie is going to have the value username:fred%20derf
The %20 represents a space. Cookie values must never have spaces, commas, or semicolons.
Javascript has the escape function which will replace odd characters with hexadecimal equivalents.

The escape() function replaced the space between "fred" and "derf" with a %20.

The line document.cookie = the_cookie; stores the cookie.