The "expires=" Substring
The cookies we've been coding so far don't live on the viewer's hard drive for very long. They are automatically deleted from the viewer's browser's cache when the browser session is ended (the browser is closed). This is fine for some applications, but often we'll want our cookie to last for days or even years.
Here's an example of what we'll be doing. The first page sets a cookie and goes to a second page that reads it. Bookmark the second page (and this one) and close all browser windows. Now reopen your browser and go directly to the second page. You'll notice that the cookie data is still available. This is not the case with our previous cookies. They expired whenever the viewer's browser was closed.
To set an expiration date on our cookie we'll be adding to our cookie's string. The cookie string can contain certain commands, called "cookie attributes", as well as text data. One of these commands is "expire=". It's added to the cookie string like this:
"some cookie data;expires=[expiration date will go here]"
There are a couple of things to note here. First is the use of the semi-colon (;). The semi-colon is of utmost importance. It is used to separate different cookie commands from the text data.
When a cookie is read, only the text up to the first semi-colon is read as data. Items following a semi-colon are processed as commands, or cookie attributes. We'll only be dealing with the "expires=" attribute in this tutorial. We'll cover more commands in the next lesson.
In fact, the string values we've been using can be set to a "name" command. You can use any substring for your "name", I'm just using "name" in the examples. You could just as well use "my_cookie=" or "joebob1=". Using different "names" becomes important when you're using multiple cookies. We'll cover this in a later tutorial.
"name=[value, the data string we'll be reading];expires=[expiration date]"
If you run into troubles with your cookie data being read, you might want to set a "name=" command to your cookie's data string.
"name=escape('My cookie data');expires=[expiration date]"
Using "name=" presents the problem of the "name=" part being read along with the data string. If you use "name=", you'll need to use "split("=")" to remove the "name=" string.
Also notice that you do not "escape()" the "expires=" command and value. You only use "escape()" and "unescape()" when dealing with a cookies data string.
It's also important to know that the "expires=" substring will not be read as data on pages reading the cookie. Only the text preceding the first semi-colon (;) is read as data. That's why the semi-colon plays such an important role. It separates the data substring, which is always the first part of a cookie string, from command substrings after a semi-colon.
Processing The Form's Data
You should already know how to code the simple form on our example's first page. To begin setting the cookie, we need to get the form's data and assign it to variables:
<script language="JavaScript">
function set_cookie(){
var name = escape(document.form1.box1.value);
var phrase = escape( document.form1.box2.options[
document.form1.box2.options.selectedIndex]
.text);
}
</script>
In the above, I've used "escape()" to encode the form data as soon as I get it. You could just as easily use the "escape()" method when setting the cookie with "document.cookie" as we have in the past.
Nothing really new here. Just basic form work. Now lets get on with setting an expiration date.
Calculating An Expiration Date
Before writing an "expires=" command to our cookie string, we need to figure out how long we want the cookie to last. This depends on the specific goal of setting the cookie in the first place.
There are four methods of calculating an expiration date:
1) You can just ignore it and add no expiration date. In this case, the cookie expires when the viewer closes their browser.
2) You can set an absolute date of sometime in the future - var date_to_die = new Date("January 1, 3000").
3) You can set a relative date to a particular number of days or years in the future - say one year from the current time. This is relative to the current time on the viewer's computer. We'll describe that process below.
4) You can set the expiration date to some time in the past just as you did when you set it to some Date() in the future. In this case, the cookie will immediately expire. This is how you "kill" cookies.
You can set the date to a specific time using the standard format used by the Date() object or GMT (Greenwhich Mean Time) format. If you are, say, setting a date in the distant future, you would first make a new Date() object for the future date and then format it to GMT format using toGMTString():
var expiration_date = new Date("January 1, 3000");
expiration_date = expiration_date.toGMTString();
The toGMTString() part just formats the Date() object into something the cookie can read. Sometimes the original Date() formatting is altered by processing and can't be read by a cookie directly. This is why it's important to get used to converting a final Date() object to GMT with the toGMTString() method. Also, pay particular attention to the capitalization in the "toGMTString()". This is the source of many errors.
Often, however, you want to set the expiration date to some time in the future relative to the current date - say a year from now. This is as opposed to a specific date in the future.
We can do this in two steps. First we make a new Date() object:
<script language="JavaScript">
function set_cookie(){
var name = escape(document.form1.box1.value);
var phrase = escape( document.form1.box2.options[
document.form1.box2.options.selectedIndex]
.text);
//creating expiration date
var now = new Date();
}
</script>
Nothing new here. If you need to, review the Date() object from the Advanced JavaScript Index.
Now we'll use the "setTime()" and "getTime()" methods to alter the current Date() object to the same date and time a year from now.
<script language="JavaScript">
function set_cookie(){
var name = escape(document.form1.box1.value);
var phrase = escape( document.form1.box2.options[
document.form1.box2.options.selectedIndex]
.text);
//creating expiration date
var now = new Date();
now.setTime(now.getTime() + 1000 * 60 * 60 * 24 * 365)
}
</script>
The new line of code might be a bit puzzling. First, note the "setTime()" method. When studying the Date() object, we emphasized getting the day, date, month, etc. It's important to know that you can set these as well. Just use "set" instead of "get" in the methods name. Pay attention to capitalization.
What we've done is made a Date() object called "now". We then use the "setTime()" method to change "now's" time. Remember that "Time" refers to the number of milliseconds that have passed between a Date() object and midnight 1 January 1970 - an arbitrary, but universally accepted standard.
The first step in changing the "Time" is to get the current time with "now.getTime()". Now we've got the number of milliseconds representing the current date and time. We add to this the number of milliseconds in a year. You'll note that I broke this very large number down into smaller ones and multiplied them. Here's how that scheme works:
1000 - The number of milliseconds in a second.
60 (first one) - The number of seconds in a minute.
60 (second one) - The number of minutes in an hour.
24 - The number of hours in a day.
365 - The number of days in a year.
In short, we've changed the value of "now" (our Date() object for the current time) to a year from the current time. Keep in mind that you can set this date to any number of days or even milliseconds you want just by adding to the current time ("getTime()"). Remember that you're dealing with milliseconds.
Adding "expires=" To The Cookie String
Now all we have to do is add "expires=" and "now" to our cookie string. Remember that the "expires=" must be separated from the cookie's data string by a semi-colon (;). Otherwise, the browser reading the cookie will consider "expires=now" part of the text data and will display it on the second page instead of setting it as an expiration date for the cookie.
Also note that you can't use different strings like you do with a cookie's "name=". You must use the exact substring "expires=". You can not use "expiration_date=" or any other string.
Before actually setting a "document.cookie", it's a good idea to check your cookie string in an alert() box. Here's the box I added when I debugged the example:
<script language="JavaScript">
function set_cookie(){
var name = escape(document.form1.box1.value);
var phrase = escape( document.form1.box2.options[
document.form1.box2.options.selectedIndex]
.text);
//creating expiration date
var now = new Date();
now.setTime(now.getTime() + 1000 * 60 * 60 * 24 * 365)
alert (name + " " + phrase +";expires=" + now);
}
</script>
Note that the semi-colon and the string "expires=" are in quotes. This is a specific text string that must be added. Now run your script in a browser and look at the text in the alert box. You should see something like:
[name typed in] [phrase selected];expires=[the date a year from now]
When the cookie is read, the substring in front of the first semi-colon is what will be read as data. The "expires=" part will be seen as a command and the expiration date for the cookie will be set. This date is not read as data. If you see your expiration date along with your data when the cookie is read on your second page, double check your syntax and make sure that a semi-colon precedes "expires=" in your cookie string.
Also, remember that you do not "escape()" the "expires=" string or the date. Only use "escape()" for the data substring.
Here's the final code for setting the cookie. I've just removed the alert() box once the string was debugged:
<script language="JavaScript">
function set_cookie(){
var name = escape(document.form1.box1.value);
var phrase = escape( document.form1.box2.options[
document.form1.box2.options.selectedIndex]
.text);
//creating expiration date
var now = new Date();
now.setTime(now.getTime() + 1000 * 60 * 60 * 24 * 365)
document.cookie = "name=" + escape(phrase) + ";expires=" + now;
}
</script>
Remember that I "escape()d" the data substrings previously. I only had to escape the spaces I wanted. Pay careful attention to the syntax. Notice the semi-colon preceding expires. It's handled inside quotes to become a literal part of the string. The semi-colon after "now" ends the JavaScript line and is not part of the cookie at all.
Reading The Cookie
A cookie with an expiration date is read just like any other cookie. Only the text up to the first semi-colon is read. The ";expires=" part is not read as data. It is read as a command.
I used a simple statement to read the cookies data substring into a variable on the second page:
var cookie_data = unescape(document.cookie);
Again, the ";expires=" part is not read as part of the data substring because of the semi-colon. This is why it's often hazardous to include semi-colons in the data substring. Using "escape()" and "unescape()" solves any such problems.
Summary & Exercises
A cookie will automatically be deleted from the viewer's cache when the browser is closed unless the cookie has an expiration date set.
To set an expiration date you need to add an "expires=[expiration date]" substring to the cookies overall string. This substring is separated from the data string with a semi-colon (;). It must be in GMT format. You can format a date object automatically using: date_object.toGMTString().
Below is a generic cookie string with an expiration date. Use an alert() box to make sure your string follows this format before writing the string to your cookie:
cookie_data;expires=[expiration date]
The above would be coded with:
escape(cookie_data) + ";expires=" + [expiration date];
After setting your cookie, with escape()d data, use an alert() box to read the data and expiration date before continuing. This box is simply:
alert (document.cookie);
OR
alert(unescape(document.cookie));
This will show you exactly what's being passed on to the cookie reading page. Note that these boxes are coded after "document.cookie" has set a cookie. Otherwise, there's no cookie to read.
For practice with this, make a cookie that will expire tomorrow. After coding the cookie setting and cookie reading pages, close and reopen your browser to the cookie reading page. The cookie data should still be there.
Now try your cookie after the expiration date and time and the cookie reading page should not display the cookie data because the cookie expired.
To Next Advanced JavaScript Lesson
Back To Advanced JavaScript Index
|