Page 1 of 1

setcookie() question

Posted: Tue Jul 20, 2004 9:09 am
by neophyte
If i set a cookie in php using setcookie(), how do you reference that cookie and put it's value into a javascript variable using javascript?

Posted: Tue Jul 20, 2004 9:22 am
by liljester
try this

Code: Select all

function setCookie(cookiename, cookievalue){
     document.cookie = cookiename + '=' + escape(cookievalue);
}

Hmmm

Posted: Tue Jul 20, 2004 9:33 am
by neophyte
I guess it's not a matter of how to set it using Javascript it's a matter of how I call it. On page one I create a cookie using php, and on page two I need to get the value of the cookie on page 2 using javascript....

Any Ideas?

Posted: Tue Jul 20, 2004 9:54 am
by liljester
well now thats a lil more interesting =) cookies are stored as a string... seperated by "; ".. then each cookie is split into a name and value by "="... like this: "autologin=true; username=myname; " so split the cookie into an array.... then split each of thos into an array and check for the name you want.. mabe something like this:

Code: Select all

function fetch_cookie(cookie_name){
     js_cookie = document.cookie.split("; ");
     for(i = 0; i < js_cookie.length; i++)&#123;
          js_crumb = js_cookie&#1111;i].split("=");
          if(js_crumb&#1111;0] == cookie_name) &#123;
               return unescape(js_crumb&#1111;1]);
          &#125;
     &#125;
&#125;

Posted: Tue Jul 20, 2004 11:44 am
by neophyte
feyd | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]


I can't seem to make the script work. It keeps returning undefined. Here's how I'm using it. First the setcookie() on page 1.

Code: Select all

setcookie("username", "Gene", 0, "/", "somesite.com", 0);

And the javascript

function fetch_cookie(cookie_name)&#123;
     js_cookie = document.cookie.split("; ");
     for(i = 0; i &lt; js_cookie.length; i++)&#123;
          js_crumb = js_cookie&#1111;i].split("=");
          if(js_crumb&#1111;0] == cookie_name) &#123;
		 
               return unescape(js_crumb&#1111;1]);
          &#125;
     &#125;
&#125;

document.write(fetch_cookie("username"));

feyd | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Tue Jul 20, 2004 12:52 pm
by liljester
unless you've modified it from what ive posted, your call to setCookie is wrong. the one i posted only takes 2 arguments. You have to set each cookie var seperatly

use the following to set the cookie "name" to equal "liljester":

Code: Select all

setCookie('name', 'liljester');

Posted: Tue Jul 20, 2004 11:28 pm
by ol4pr0
Adding dir would be smart aswell and or time

ie

Code: Select all

setCookie('name', 'liljester','time()+3600','/');