Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Aug 2010
    Thanked 0 Times in 0 Posts

    Javascript cookies

    Hi all,

    I've been trying to set, get and delete js cookies for a while now, although they seem to set (from what I can tell) I can't seem to do what else I need with them.

    This is what I'm trying to do:

    Function1 - setCookie (sets a cookie called 'saveAndExit' - that's it, no expiry date)

    Function2 - useCookie (checks to see if a cookie called 'saveAndExit' exists and if it does alert("COOKIE WORKS") and then deletes the cookie

    If it doesn't exist alert("cookie does not exists")

    Could anyone assist with this? It's been driving me insane for days!


  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    London, England
    Thanked 2,573 Times in 2,551 Posts
    Cookies have been covered very many times in this forum. Have you tried the search feature? It is rather tedious to have to constantly repeat the same scripts/solutions. Here is a basic cookie script:-

    <body onload ="readCookie('mycookie'); eraseCookie('mycookie'); createCookie('mycookie','anyvalue', 7)">
    <script type = "text/javascript">
    function createCookie(name,value,days) {
    if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    var expires = "; expires = "+ date.toGMTString();
    else var expires = "";
    document.cookie = name + "="+ value + expires + "; path=/";      // available throughout the directory
    function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) {;
    retval = c.substring(nameEQ.length,c.length);
    alert (retval);  // for testing
    return retval;
    return null;
    function eraseCookie(name) {
    createCookie(name,"",-1);  // set cookie to expire on previous day
    name = "mycookiename" or whatever name you wish to give the cookie
    value = "anything" 
    days = number of days cookie to remain active (say 7)
    It is your responsibility to die() if necessary….. - PHP Manual
    Last edited by Philip M; 08-04-2010 at 12:52 PM.


    Posting Permissions

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