Reputation: 469
So i am setting cookies here. They are totally working since when i go onto my firefox privacy thing, i can see the cookie there and its value, but the moment i am trying to read it or to echo it, it is always giving me a blank result...
I am using Wordpress, and i call the setcookie with an ajax request from a click of a button. Here how i do it under here :
This script is inside templateDirectory/js
$('.bucket-list').on("click", function () {
$.ajax({
url: templateDir + '/js/list.php'
});
Inside the php file list.php, we have this :
setcookie("displaymode", "list" , time() + 3600 * 24 * 30);
Up to here as i said i can see the cookie inside my browser, but when i try to call it, it just keep on giving me blank result, like this :
if ($_COOKIE["displaymode"] == "list")
echo '<div class="class1">' ;
else {
echo '<div class="class2">' ;
echo '<script>';
echo 'alert('.$_COOKIE["displaymode"].')';
echo '</script>';
}
?>
this script up there is located in the main file (homepage.php) from the templateDirectory. Any help would and will be greatly appreciated.
Upvotes: 0
Views: 1318
Reputation: 5981
From PHP documentation, in common pitfalls:
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires.
Upvotes: 0
Reputation: 57709
Make sure the cookie is set on the expected path.
If your script is in:
/templates/MyTemplate/js/list.php
The cookie will be set for the path /templates/MyTemplate/js/
.
To set the cookie for the whole domain use:
setcookie("displaymode", "list", time() + 3600 * 24 * 30, "/");
set path to "/" --^
Upvotes: 3
Reputation: 31614
Remember that cookies cannot be set and called on the same page. You have to have a page load in between. That's why people tend to gravitate towards sessions, which can be set and called on the same page (the session data is not stored in the cookie)
Upvotes: 2