SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Thread: Delete Cookie

  1. #1
    SitePoint Zealot
    Join Date
    May 2002
    Location
    RI-USA
    Posts
    113
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Delete Cookie

    I have never used javascript before, so this is extremely foreign to me. But I was wondering how to delete a cookie in javascript. I've searched on google and it says to set the expired date to something in the past, but I'm not sure how to do that. One problem is I don't know the name of the cookie, and how would I execute the delete function once i have figured out the name of the cookie? Here's the code I used to create the cookie.

    Code:
    <script>
    <!--
    // give feedback to the respondent about the state of their submission
    
    function AllowNoDups()
    {
       var cookie_ls = document.cookie;
       if (cookie_ls.indexOf(document.location) > -1)
       {
          alert("You have already completed this form. Thank you for visting!  ");
          return false;
       }
       else
       	{
    var exp = new Date();
    exp.setTime(exp.getTime() + 24*60*60*90*1000);
    var expDate = exp.toGMTString();
          document.cookie = window.location.href + " from " + document.referrer + "; path=/; expires=" + expDate;
    
          return true;
       };
       };
      //-->
    </script>
    Then on the form tag itself I have
    Code:
    <form onSubmit="return AllowNoDups();" ... >
    Thanks.

  2. #2
    American't awestmoreland's Avatar
    Join Date
    Sep 2002
    Location
    Grand Rapids, MI
    Posts
    1,168
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The naming problem is easy enough.
    I use Analog X's Cookie Wall which gives me details on each new cookie created and allows me to accept/deny it.
    The alert that occurs when running your code locally on my machine clearly shows that no name has been assigned to it.
    (See screenshot).

    The best way to create a cookie seems to be to assign the cookie contents to a variable and then name the cookie when creating it using the assigned data.
    e.g. to create a cookie called "the_cookie":
    Code:
    var cookie_data = "the_cookie=" + escape("username:" + the_name);
    document.cookie = cookie_data;
    Check out Web Monkey for more details on this.

    To delete the cookie, you can just reset the date to one earlier than the current date as you suggested.
    ScriptBreaker.com has some cut and paste functions that you can use for this purpose.

    Also while investigating this, I discovered a handy tool at builder.cnet.com for creating cookie code which you might find useful.


    Hope that helps,

    Andy


    Resources mentioned in this post:
    From the English nation to a US location.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •