Reputation: 179
Ok I have a javascript cookie , and it work on current page of site (www.example.com/about.php), but on the index page of the site (www.example.com), it is not working. It says the cookie is not set.
I wana to display cookie value in another page. Any ideas?
Here is my code:-
in www.example.com/about.php page on click event of button:-
var cookievalue="testingCookie";
document.cookie="stateNcity=" + cookievalue;
var a=document.cookie;
alert(a);
and in www.example.com:-
<div id="abcd">click</div>
$("#abcd").on("click",function()
{
var cookie_string = document.cookie;
if (cookie_string.length !=0)
{
alert(cookie_string);
}
else
{
alert('cookie is not set');
}
});
Upvotes: 2
Views: 3004
Reputation: 15827
As you set a cookie you should specify an expire time and a path. If you don't specify a path the cookie is accessible only by the current page.
See for reference: http://www.w3schools.com/js/js_cookies.asp
For example:
var cookievalue,
cookieexpire,
cookiepath,
date;
cookievalue ="testingCookie";
date = new Date();
date.setTime(date.getTime() + 3600 ); // will last 3600 seconds (1 hour)
cookieexpire = date.toGMTString();
cookiepath = "/"; // accessible from every web page of the domain
document.cookie="stateNcity=" + cookievalue + "; expires=" + cookieexpire + "; path=" + cookiepath;
It is quite obviuos then but as the user navigates to www.example.com the cookie will result as set only if he/she has first visited www.example.com/about.php and triggered the click.
Cookie management in pure JavaScript is not trivial.
As you tagged your question with jquery
I suggest using it for cookie management, see https://stackoverflow.com/a/1458728/1579327
Upvotes: 3