views:

206

answers:

2

Hello,

My question is if I can set a cookie using javascript (and read it)

My first impression is that the code beneath doesn't work If I look in my vista cookie folder, I can not the name off the cookie

    function zetCookie(naam,waarde,dagen) {
    if (dagen) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var verloopdatum = "; expires="+date.toGMTString();
    }
    else var verloopdatum = "";
    document.cookie = naam+"="+waarde+verloopdatum+"; path=/";
}    

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) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

thanks,Richard

A: 

I can't answer why the cookie is not showing in your Vista folder, but that code properly sets and reads cookies as intended. How are you testing it? An easier way to test whether the cookies are sticking is by simply doing something like this:

<input type="button" value="Set" onClick="createCookie('test','yay',5);">
<input type="button" value="Read" onClick="alert(readCookie('test'));">

You can refresh the page between Setting and Reading it if makes you feel better, but it works for me.

If that doesn't show what you're expecting, make sure your browser is setup to accept cookies. :)

EDIT: Looking at your code, you missed replacing days in this line:

date.setTime(date.getTime()+(days*24*60*60*1000));
Paolo Bergantino
it accepts cookies, because I can see lots off themuser@somecookie....
How are you setting the cookies? I added a link to a sandbox where I tested the code and it works fine.
Paolo Bergantino
also, does the readcookie() ignore the user@ that goes before the cookiename?
Maybe. I'm not really familiar with how browsers store the cookies or whatever, so I can't really comment on the user@ part.
Paolo Bergantino
it is definitivly something in the syntax, because it stops execution off the code from the point it runs into the function that supposed too set the cookie
Can you edit your question to show the code you are using to test the functions?
Paolo Bergantino
I know it, I diddn't change all off the variable names in my translation (see days), sorry, better post the code that I actually use.
A: 
  1. Install Firefox
  2. Install FireBug
  3. Install FireCookies
  4. Download JQuery
  5. Download the Cookie plugin
Jonathan Parker
6. Add a dependency and overhead that you may not need...
Zack Mulgrew