setcookie() question
Moderator: General Moderators
setcookie() question
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?
try this
Code: Select all
function setCookie(cookiename, cookievalue){
document.cookie = cookiename + '=' + escape(cookievalue);
}Hmmm
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?
Any Ideas?
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++){
js_crumb = js_cookieїi].split("=");
if(js_crumbї0] == cookie_name) {
return unescape(js_crumbї1]);
}
}
}feyd | Please use
feyd | Please use
Code: Select all
andCode: 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){
js_cookie = document.cookie.split("; ");
for(i = 0; i < js_cookie.length; i++){
js_crumb = js_cookieїi].split("=");
if(js_crumbї0] == cookie_name) {
return unescape(js_crumbї1]);
}
}
}
document.write(fetch_cookie("username"));feyd | Please use
Code: Select all
andCode: 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]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":
use the following to set the cookie "name" to equal "liljester":
Code: Select all
setCookie('name', 'liljester');Adding dir would be smart aswell and or time
ie
ie
Code: Select all
setCookie('name', 'liljester','time()+3600','/');