spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

Quality, Affordable Dental Plans from DentalPlans.com
Developer News
Sir Tim Talks Up Linked Open Data Movement
From L.A. to Vegas With 100GbE
Salesforce Rolls Out Big Summer '08 Update
JavaScript Tip of the Week for November 25, 1996: Everything You Ever Wanted to Know About Cookies




Every time you come to this tip, it is going to remember your name. Have I used some secret, undocument JavaScript feature to do this? Nope, just the Cookie. The Cookie, which is a part of Netscape and Internet Explorer, is a small file filled with little tidbits of information. It is secure, easy to use, and possibly the only practical way to store data over long periods of time using JavaScript.

There are two functions (three if you want to delete) that you need to be able to write to and read from a browser's Cookie. The most prevalent code out their is Bill Dortch's, but for the sake of this tip I wrote my own functions. These functions, which only access the cookie once per call, are twice as fast as Dortch's. See for yourself. I say this only because if you are currently using a lot of Cookies in your site, you might want to switch to these faster more efficient functions. For now, you will not need to understand exactly how these functions work, but you will need to know how to use them. The first function is used to save to a cookie:
    function setCookie (name, value, expires) {
        if (!expires) expires = new Date();
    document.cookie = name + "=" + escape (value) +     <-- save cookie value
    "; expires=" + expires.toGMTString() +  "; path=/"; <-- set expiration date
    }                                                       and universal path
If you are a little confused with how this function works, don't worry. It is more important that you understand how it is used to save information. For instance, if you want to save someone's first name (such as Bob) to a cookie called "_name", these three lines are all you need:
        var expdate = new Date ();
        expdate.setTime (expdate.getTime() + (1000 * 60 * 60 * 24 * 31));
        setCookie ("_name", "Bob", expdate);
First this function gives the cookie an expiration date (how long it will exist before it is erased) of one month. The one month is set by multiplying 1000 milliseconds by 60 seconds by 60 minutes by 24 hours by 31 days (say that ten times fast). If you want to save the cookie for a year, change the 31 to a 365. All cookies must have an expiration date, and a month is plenty of time. If you specify no expiration date, then the cookie will only last through the current browser session. So, setCookie() is run: It creates a cookie called "_name", sets the value of the Cookie to "Bob", and sets the expiration date to 31 days.

To read data off of the Cookie, use this more elaborate function:
    function getCookie (name) {
    var dcookie = document.cookie; 
    var cname = name + "=";
    var clen = dcookie.length;
    var cbegin = 0;
        while (cbegin < clen) {
        var vbegin = cbegin + cname.length;
            if (dcookie.substring(cbegin, vbegin) == cname) { 
            var vend = dcookie.indexOf (";", vbegin);
                if (vend == -1) vend = clen;
            return unescape(dcookie.substring(vbegin, vend));
            }
        cbegin = dcookie.indexOf(" ", cbegin) + 1;
            if (cbegin == 0) break;
        }
    return null;
    }
This function searches through the Cookie until it finds the Cookie name that you specify. Then it finds the value of the Cookie and returns it. To get the Cookie that was saved with "Bob's" name in it, "_name", you would use a simple line of code like this:
    document.write(getCookie("_name"));
This would print out the value of the "_name" cookie, which was set to "Bob". If you wanted to print out the value of some other cookie, you would just use it's name in place of "_name". You can give the value of a cookie to a variable, allowing you to manipulate the values and create programs that can save and load information. But keep in mind that you will need to include both functions: setCookie() and getCookie(), to do anything with the cookies.

Finally, if you wish to erase a Cookie that you set, use this simple function and pass it the name of the doomed Cookie. However, you can only delete (as well as get and set) a cookie that was created in your domain. That's simply a saftey precaution; to make sure we don't go around "stealing each other's cookies".
    function delCookie (name) {
    var expireNow = new Date();
    document.cookie = name + "=" +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT" +  "; path=/";
    }
Now read on and learn some creative ways to use Cookies...

Source



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM eBook: Planning a Service Oriented Architecture
IBM eBook: Choosing the Right Architecture--What It Means for You and Your Business
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Avaya Article: Using Intelligent Presence to Create Smarter Business Applications
Intel Go Parallel Article: Getting Started with TBB on Windows
Microsoft Article: 7.0, Microsoft's Lucky Version?
Avaya Article: How to Feed Data into the Avaya Event Processor
IBM Article: Developing a Software Policy for Your Organization
Microsoft Article: Managing Virtual Machines with Microsoft System Center
Intel Go Parallel Article: Intel Threading Tools and OpenMP
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Silverlight 2 App and Walkthrough: Leverage Silverlight 2 with SQL Server and XML
IBM Article: Enterprise Search--Do You Know What's Out There?
HP Demo: StorageWorks EVA4400
Microsoft Article: The Progress and Promise of Deep Zoom
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
webref The latest from WebReference.com Browse >
Book Review: Head First JavaScript · Web Hosting Control Panels · Use Your Blog for Fast Search Engine Rankings
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
NetApp's Virtual Storage Strategy Crystallizes · F/MC Watch: A Cisco-Centric Approach · Olympic Time Trials Use Wi-Fi Mesh