Setting and Reading Cookies
Introduction. Whenever you visit a web site, whether operating on the client or server side, or both, almost none of the history of your activity on the site is retained. Web interactions are designed to be inherently stateless. That is, in its simplest and most common form, you submit a request to the host server and the HTML is downloaded to your browser which interprets and displays it. The host server doesn't automatically retain any information about your interaction so far.
In order to retain information during the entire connection session or beyond this particular session, the developer needs to build in other options. For example,
These are the most common ways that information can be made to persist for a user, databases, session variables and cookies. Though it is important to remember that cookies do not persist for longer than the current session unless particular properties are set.
Cookies are stored in a file on the client's computer. Their location and formatting on the client depend on what browser you are using when you visit the site.
First we will set a cookie and read the cookie after it has been set. You should copy the following code into a file called DateTimeCookie.html.
<title>Set a Date Time Cookie</title>
var the_date = new Date();
var the_cookie = "date=" + escape(the_date);
document.cookie = the_cookie;
var the_cookie = document.cookie;
var the_cookie_array = the_cookie.split("date=");
var the_date = unescape(the_cookie_array);
document.write("<P><font size=5><b>The last time you visited here was: " + the_date + "</b></font></P>");
<body bgColor="666699" text ="330033">
<table align="center" width="500">
<td align="right"><input type="Button" value="Set The Cookie" onClick="setCookie();"></td>
<td align="left"><input type="Button" value="Read The Cookie" onClick="readCookie();"></td>
|This code has two different functions that can be
invoked by clicking on a form button.
The setCookie( ) function sets the cookie to be the current date and time when you press the button.
The readCookie( ) function reads and display the values you most recently set for the cookie that has been written to your computer.
I have used alert( ) functions to display basic information along the way. At some step you are likely to see something like the following.
|The unusual formatting appears because you have invoked
the escape( ) function to translate the date.
After having clicked on the Read The Cookies button you should see something like the following.
|You need to make sure about what form your cookies are
in at any particular point in time, escape( ) or unescape( ).
Who can actually read a cookie depends on how they were setup. By default they can only be read by the page that set them. Another default is that they persist only for the duration of the current session. In the next page we work on how the developer can control both of these things according to their needs.