PDA

View Full Version : Cookie Setting



Deadweight
03-26-2014, 01:08 AM
I have been trying to set a cookie and use an alert to check to see if the cookie was actually set; however, it seems like it is failing to set the cookie:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Game Selection</title>
<style>
* { margin:0 auto; padding:0;}
body { background-color:#CCCCCC;}

#play { width:200px; border:1px solid black; text-align:center; margin-top:5px; cursor:pointer; background:white;}
#play:hover { text-decoration:underline;}

#bce_popup {
position:absolute;
top:0;
left:0;
background-color:black;
background-color: rgba(0,0,0,0.85);
width:100%;
height:100%;
display:none;
}

#bce_main {
top:10px;
height: 80%;
width:80%;
margin-top:10px;
clear:both;
position:absolute;
display:none;
background-color:transparent;
border:1px solid black;
background-color:white;
margin-left:10%;
}
</style>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).on('click','#play',function(){
document.cookie=escape("username=xxx xxx; expires=Thu, 18 Dec 2014 12:00:00 GMT; path=/")
alert(document.cookie);
})

</script>
</head>
<body>

<div id="play">Display</div>

</body>
</html>

traq
03-26-2014, 03:46 AM
You're escaping the entire string (including all the settings). You should only be escaping the value part:
document.cookie="username="+escape("xxx xxx")+";expires=Thu, 18 Dec 2014 12:00:00 GMT;path=/";
alert(document.cookie); // alerts "username=xxx%20xxx"

Using your original code, however, the cookie was set (the alert showed its name was the entire encoded string, and it had no value). Did you get different results?

Deadweight
03-26-2014, 04:18 AM
This is weird. Nothing is appearing for me. It says javascript alert but in the message part it is blank? Also, yours is the same way. I tried it on Chrome and Opera

traq
03-26-2014, 08:49 AM
Dunno.

To be clear, I'm testing only the document.cookie part; I haven't included the onclick or any of the markup.
Does this demo (http://jsfiddle.net/traq/w5acW/) work for you?

Deadweight
03-26-2014, 12:12 PM
Yes that works, do cookies not work if they are local?

traq
03-26-2014, 07:13 PM
Are you using a local server (e.g., http://localhost), or just opening the file from your desktop?

Deadweight
03-26-2014, 07:45 PM
Just opening the file like a normal HTML. Do i need to use my localhost with XAMPP?

traq
03-26-2014, 10:27 PM
Well, I wouldn't have thought so, but after testing on Chrome it appears you might: I get a blank cookie that way too. You have xampp installed? give it a try.