Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Cookie not being set for all pages



3:03 pm on May 26, 2012 (gmt 0)

5+ Year Member

I'm using the following code to set a cookie:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
function SetCookie(c_name,value,expiredays)
var exdate=new Date()
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
{ ?>
<div id="eucookielaw">
<a href="#" id="removecookie" onClick="SetCookie('eucookie','eucookie','100')">Accept this cookie</a>
<?php } ?>
$("#removecookie").click(function () {

So when the user clicks the "Accept this cookie" link it will set the cookie and close the div. If the user comes back to the page then it checks if that cookie exists and then doesn't show the link if it does exist.

The problem I have is that I have this in the header of my site and if I visit the homepage directly the cookie sets the path as "/" and so further pages do not show the "Accept" cookie link. If however

If however I navigate to a page off of the root i.e. /about then it will set the cookie but then going back to the homepage the "Accept" link remains and I have to click it again.

Not quite sure what I'm doing wrong?


8:05 pm on May 26, 2012 (gmt 0)

5+ Year Member

I've managed to resolve a bit of this by changing the code to:

document.cookie=c_name+ "=" +escape(value)+";path=/"+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())

Notice the "path" addition.

What I'm struggling with now is getting this bit to work

{ ?>
Show this here
<?php } ?>

The problem is the user has to refresh the page before this takes affect, I'm presuming because the page is still in the cache.

Any ideas?


4:47 pm on May 29, 2012 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

Well that's not why it does that. A cookie is set in the browser and can't be read until the next page load because it's a single direction communication. You can't set it and read it at the same time.

You're probably going to need to do a location reload/redirect to the same page after setting a cookie.

Featured Threads

Hot Threads This Week

Hot Threads This Month