In this article, find out how to store and retrieve persistent data with cookies, small files that allow you to do big things. This article explains the basics of cookies, demonstrates reading and writing them in JavaScript, and illustrates their use in a real-world application.
Now, that was pretty simple -- but there's more than one way to skin a cat. If you're in a rush and don't have too much time to spend on implementing a custom cookie library, the Web throws up a number of interesting public-domain libraries which are powerful, stable and easy to use.
The best-known of these public-domain cookie libraries is the one created by Bill Dortch in 1996, and used extensively in many sites on account of its rich features and overall stability. Coincidentally, this is also the library I plan to use throughout the rest of this tutorial, so drop by and download a copy before reading any further.
Once you've got yourself a copy of the library, copy it to your development area, and create the following simple HTML document (remember to use the correct path to the library when linking to it in the JavaScript tags):
<html> <head> <script language="JavaScript" src="cookieLibrary.js"></script> <script language="JavaScript" type="text/javascript"> function writeName() { // get user input from form field var user = document.forms[0].elements[0].value;
// calculate expiry date 1 hour from now var d = new Date(); d.setTime(d.getTime() + (60 * 60 * 1000));
// write value to cookie SetCookie("username", user, d); alert("Data written successfully"); } </script> </head>
<body> <form>
Enter your name <input type="text" name="username" size="10"> <input type="button" onClick="javascript:writeName()" value="Save!"> </form>
</body> </html>
With the Bill Dortch library, setting a cookie is as simple as calling the SetCookie() function with appropriate arguments. The first two of these arguments are the mandatory name and value parameters - these must be set for the cookie to be valid. For persistent cookies, you would also follow these two arguments with an expiry date set to 60 minutes ahead of current time (60 minutes * 60 seconds * 1000 milliseconds); this will ensure that the cookie is saved to the hard drive and remains valid for 1 hour. For non-persistent (session) cookies, simply omit this expiry date.
Here too, once you've entered your name into the form and hit the "Save!" button, your cookie will be saved to disk in your browser's cookies directory. If you look at the code for the SetCookie() function, you'll see that internally, it does pretty much the same thing you manually did in the example on the previous page.