What to do with cookies
Now that you know how to manage cookies using JavaScript, what can you do with this knowledge? I will give here two simple examples. Both examples assume that you are using the routines given earlier in this tutorial. The first example shows how to greet a user by his name. We read a cookie called 'name'. If it does not exist, we prompt for a name and send a cookie to store the name for one year. If the cookie exists, we welcome the user. This script should be placed within the body of the page.
<SCRIPT LANGUAGE="JavaScript">
var today = new Date();
var expires = new Date();
expires.setTime(today.getTime() + 60*60*24*365);
var usrname = getCookie("name");
if ( usrname == null ) {
usrname = prompt("Give me your name, please", "");
setCookie("name", usrname, expires);
document.write("<P>Greetings, ", usrname);
}
else {
document.write("<P>Welcome back, ", usrname)
}
</SCRIPT>
The second example is along the same lines but a little more convoluted and tries to establish certain degree of safety in accessing the site. The user is derived to an error page if he refuses to give his name, and even when he do so, the name is passed to a script that presumably checks it against a database of user names. Of course, it is not my purpose to show here a bullet-proof login method.
<HTML>
<HEAD>
<TITLE>Test cookies</TITLE>
<SCRIPT LANGUAGE="JavaScript">
... include cookie routines here...
</SCRIPT>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
var today = new Date();
var expires = new Date();
expires.setTime(today.getTime() + 60*60*24*365);
var usrname = getCookie("name");
if ( usrname == null ) {
usrname = prompt("Give me your name, please", "");
if ( usrname != null ) {
setCookie("name", usrname, expires);
}
else {
document.location.href = 'error.html';
}
}
</SCRIPT>
<TABLE>
<TR>
<TD>
Hello,
<SCRIPT LANGUAGE="JavaScript">
document.write(usrname);
</SCRIPT>
</TD>
</TR>
<TR>
<TD>
<P>Press the button to get in!</P>
</TD>
</TR>
<TR>
<TD>
<FORM action="/cgi-bin/checkId.pl" method="POST">
<SCRIPT LANGUAGE="JavaScript">
var content = '<INPUT type="hidden" name="login"
value="' + usrname + '">';
document.write(content);
</SCRIPT>
<INPUT TYPE="submit" VALUE="Click here">
</FORM>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
|
Previous | Contents | Next
|