I am trying to set a cookie in jquery using :
$( "a.Edit" ) .click(function() {
$( "#dialog-form" ).dialog( "open" );
var un=$(this ).text();
$.cookie("test", un);
});
but when i use it after that <?php echo $_COOKIE['test'] ?> it wont work the cookie is still not set
any help please
thanks in advance
Use the jquery_cookie() plugin for this.
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
Where the_cookie is the name of your cookie. and where the_value of your cookie is the value/function it has to do.
expires 7 means that the cookie wil expire in 7 days (one week)
Path isn't nessesary,
Define the path where the cookie is valid. By default the path of the
cookie is the path of the page where the cookie was created (standard
browser behavior). If you want to make it available for instance
across the entire domain use path: '/'. Default: path of page where
the cookie was created.
You can remove the cookie using:
$.removeCookie('the_cookie');
you can read the cookie using:
$.cookie('the_cookie');
Hope it helps.
It is possible to set the cookie in PHP entirely without jQuery at all..
..however...
It appears you are using jQuery in this way.
What may be causing a problem is a few things:
a) $(this).val() possibly might be returning NULL.
b) You are not setting the path and expiration on the cookie.
If you have subdirectories it is normally good to set a master cookie that is the root path '/'.
To read your cookie using PHP, try this...
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
Can be possible duplicate of Get the cookie value in PHP?
Try using:
$.cookie("example", "foo", { expires: 7 });
Source
Related
So I'd rather not use JS/jQuery for this - but I can't seem to get this to work.
I've got a link Hide Updates which I'm trying to set a cookie with.
if($_GET['hideupdates'] == 'hide'){
setcookie("HideUpdates", "hide", time()+60*60*24*5, "/", $vars->networkSite);
}
it "works", but I have to click the link twice.
from "site.com" I can var_dump() the cookie and it comes up NULL
Now I click the link and go to "site.com?hideupdates=hide" and the cookie still comes up NULL
However, from "site.com?hideupdates=hide" when I click the link again - THEN the cookie comes back hide.
Am I missing something? Or do I 'have' to use JS/jQuery for this?
setcookie does not affect the current request. To do that, you also need to manually set the relevant $_COOKIE variable:
setcookie("HideUpdates",$_COOKIE['HideUpdates'] = "hide", time()+60*60*24*5, "/", $vars->networkSite);
The only way to do it is JS or jQuery because, as the other people say, cookies does not affect the current page request.
You need jquery cookie plugin for the jQuery solution. Some servers have problems with jquery.cookie.js (The solution is to rename the file E.g.: jquery.cook.js)
Usage of jquery cookie plugin
Create session cookie:
$.cookie('the_cookie', 'the_value');
Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });
Create expiring cookie, valid across entire site:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
Read cookie:
$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined
Read all available cookies:
$.cookie(); // => { "the_cookie": "the_value", "...remaining": "cookies" }
Delete cookie:
// Returns true when cookie was found, false when no cookie was found...
$.removeCookie('the_cookie');
// Same path as when the cookie was written...
$.removeCookie('the_cookie', { path: '/' });
You can try localStorage. It works on Chrome, FF and IE9 and up. We do not support IE7-10! Hooray!
IE8 have some issues with localStorage.
Script must be inside the $(document).ready(function() {});
$(document).ready(function() {
$("#btnClick").click(function(e) {
e.preventDefault();
localStorage.setItem('cookieName', 'cookie_value');
window.href.location = "your_new_page.php";
});
//On the same page or other page
if (localStorage.getItem('cookieName')){
//do here what you want
}else{
//do something else
}
});
Cookies don't kick in until after they are set and a new page request is sent. This is because cookies are sent with page requests, they just don't magically appear to a the server.
Your solution is to do a page refresh after setting the cookie.
EDIT: MY BAD, IT WAS A (SERVER SIDE) CACHING ISSUE. Thanks for the help.
I have a site that when visited first checks for cookie "intro" and then if it doesn't exist, redirects it to an intro page.
<?php if (!isset($_COOKIE["intro"])) {
header( 'Location: http://explainasterisk.com/intro/' ) ; } ?>
When the user clicks the "begin" button on the intro page, the cookie is set using:
<script type="text/javascript">
$(document).ready(function () {
$('.home').click(function () {
scroll(0, 0); //scrolltotop
var intro = "intro" //setting cookiename variable
var today = new Date();
var expire = new Date();
expire.setTime(today.getTime() + 3600000*24*365);
document.cookie = intro+"=1"
+ ";expires="+expire.toGMTString();
$('.home').slideUp(3000, function () { //slideUp function
//Nothing
});
});
});
</script>
In Opera and Chrome the cookie is being set, but when I click on the skip button on the intro page (that takes me back to the original page), I'm simply redirected to the Intro page. You can see this live here: http://explainasterisk.com/
if (!isset($_cookie["intro"])) {
is incorrect array name. It should be in CAPS, like this
if (!isset($_COOKIE["intro"])) {
Reference: $_COOKIE
Thanks Brad Christie.
The source of you problem is you don't have error_reporting(E_ALL); in the beginning of your code (and ini_set('display_errors','On'); in development environment).
If you have it, PHP will display error message that there is no $_cookie variable.
You might want to give jquery-cookie a try because it makes setting and handling cookies in javascript with expire dates so much easier.
One simple line:
$.cookie("[cooke name]", "[value]", { expires: [time in days]);
e.g.:
$.cookie("intro", "set", { expires: 365);
Your PHP snippet looks fine to me and - if the cookie is set correctly - should work.
Try adding the path and domain to the end of your cookie:
path=/; domain=.<?php echo $_SERVER['HTTP_HOST']; ?>
the cookie in javascript is being set with domain .explainasterisk.com
So try this before reading the cookie.
ini_set("session.cookie_domain", ".explainasterisk.com");
So I'd rather not use JS/jQuery for this - but I can't seem to get this to work.
I've got a link Hide Updates which I'm trying to set a cookie with.
if($_GET['hideupdates'] == 'hide'){
setcookie("HideUpdates", "hide", time()+60*60*24*5, "/", $vars->networkSite);
}
it "works", but I have to click the link twice.
from "site.com" I can var_dump() the cookie and it comes up NULL
Now I click the link and go to "site.com?hideupdates=hide" and the cookie still comes up NULL
However, from "site.com?hideupdates=hide" when I click the link again - THEN the cookie comes back hide.
Am I missing something? Or do I 'have' to use JS/jQuery for this?
setcookie does not affect the current request. To do that, you also need to manually set the relevant $_COOKIE variable:
setcookie("HideUpdates",$_COOKIE['HideUpdates'] = "hide", time()+60*60*24*5, "/", $vars->networkSite);
The only way to do it is JS or jQuery because, as the other people say, cookies does not affect the current page request.
You need jquery cookie plugin for the jQuery solution. Some servers have problems with jquery.cookie.js (The solution is to rename the file E.g.: jquery.cook.js)
Usage of jquery cookie plugin
Create session cookie:
$.cookie('the_cookie', 'the_value');
Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });
Create expiring cookie, valid across entire site:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
Read cookie:
$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined
Read all available cookies:
$.cookie(); // => { "the_cookie": "the_value", "...remaining": "cookies" }
Delete cookie:
// Returns true when cookie was found, false when no cookie was found...
$.removeCookie('the_cookie');
// Same path as when the cookie was written...
$.removeCookie('the_cookie', { path: '/' });
You can try localStorage. It works on Chrome, FF and IE9 and up. We do not support IE7-10! Hooray!
IE8 have some issues with localStorage.
Script must be inside the $(document).ready(function() {});
$(document).ready(function() {
$("#btnClick").click(function(e) {
e.preventDefault();
localStorage.setItem('cookieName', 'cookie_value');
window.href.location = "your_new_page.php";
});
//On the same page or other page
if (localStorage.getItem('cookieName')){
//do here what you want
}else{
//do something else
}
});
Cookies don't kick in until after they are set and a new page request is sent. This is because cookies are sent with page requests, they just don't magically appear to a the server.
Your solution is to do a page refresh after setting the cookie.
I use the Laravel PHP framework and set a cookie using Cookie::put(..),
Code to set cookie using Laravel PHP,
Cookie::put('id', $id , 0, '/');
when I looked into it I found cookie is being set to a root path that's good for me.
Now in JS I use a jQuery plugin to read the cookie but it returns null while reading cookie setted by PHP.
JS code to access cookie,
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name){
return unescape(y);
}
}
}
print_r($_COOKIE)
Array ( [id] => 653a8dbd0903d2eacfdfe87bce29640d136a4380+1 [session_payload] => 2c3e260bb766ea1519dcbc3d13025d3ede6e2e63+mSfAHUAPvmFefQbIArozzbQfY0IzZpAeTarpQsHHOseN+SD3xmmUWfUduVYWf7qVu1Rwo2XYIBSBTUt+J1DhbE9sN2yEelpjsHzU0CVw3F1aPpcPh6oSTzIfskr2hHuWIGi5sf1lvD7qRHtcjPOBD700vnQSy2+DIMTNT4eMS7pz85zi9TMpgLQfWbtUUtNQk1SRHwncwgQyp1xhgPqp4d6eLjaZQ2hXBtOgYbC2Ty5xS4e76WCW+dumNMj3hkSfMoDssKnmRTzV7jYUT6a+oH26tZkKOR8EMMh04xHMWlt73aFsL9EZrIXZFKHkOXqU883qThWot//emOpakBKWyA== [laravel_session] => 2729bdfca6fe6e6f3c98d03c11a65915649af09b+ML1G6xZ5YkImViUxm9gOaTo5AT8jyBfqagdoeyAs ) 1
Update:
I really don't know why this was voted down but here,
I want to access the cookie using JS previously added using PHP.
If COOKIE expiry set to 0, the cookie will expire at the end of the session (when the browser closes). So, JS will not read expired COOKIEs
Try setting the COOKIE expiration for longer,
Cookie::put('id', $id , time()+3600, '/'); //set the cookie alive for 1 hour
Is there any way of instructing a web browser to completely delete one's cookie set with PHP?
I do not want to expiry it or wait for the browser to be closed.
With delete I mean to actually not have it listed inside the cookie's list anymore.
Try something like this to delete all cookies:
foreach ($_COOKIE as $name => $value) {
setcookie($name, '', 1);
}
The value 1 is the expire value and it represents one second after the begin of the Unix time epoch. So it’s always already expired.
You cannot force the browser to delete the file associated with any cookie, because you can't guarantee there's actually such a file - the contract between browser and web server regarding cookies is that the data will be presented at eligible requests.
You state that you "don't want to wait for the cookie to expire", but cookie expiration is the correct method for indicating that the data is no longer needed and should not be presented on future requests, which in most cases does translate to the browser removing the file.
To delete a cookie, therefore, set its expiration time into the past. In PHP, this is done with setcookie().
Yes. Use setcookie() and set the expiration date for the cookie you wish to delete to a time in the past. The user's browser should automatically remove it as a result.
'Seems that deleting a cookie is more difficult than it looks.
setcookie($name, '', 1);
Won't do the trick. The '' is empty and setcookie can ignore the whole instruction.
Also setting the time to the past sometimes allows the cookie to retain the value whose expire time is newer than 1.
I am dealing with this right now. I don't know where it comes from, but it's there.
I've resorted to
setcookie($name, '0', 9000000000);
This ensures the cookie is set to a value that resolves to false and that it is newer than any previous value.
If anyone has any insight into this behavior please tell.
I suspect the difficulty lies in the fact that the domain and path values for setcookie are guaranteed to be the same from execution to execution when the values are not specified.
And I am aware such a cookie will not expire until 2038 or so.
Alternately, if the newest expiration date of the cookie is known, it need be set only 1 second after.
I think that you have to use combined approach:
set expiration way back in the past (as suggested by Chacha102)
use JavaScriptto delete entries from document.cookie DOM object (as suggested by andres descalzo)
There are 2 good reasons for going with mixed approach:
JavaScript can be disabled in the browser
not all cookies are visible in document.cookie Some modern browsers are supporting httponly flag for cookies. PHP has support for httponly cookies, see http://www.php.net/setcookie
I wrote this plugin for me and works correctly.
(function($) {
$.cookieAllDelete = function(doc)
{
var cookie_date = new Date();
var cookies = null;
cookies = doc.cookie.split(';');
cookie_date.setTime(cookie_date.getTime() - 1);
for(var i=0; i < cookies.length; i++)
{
var cookie_name = cookies[i].split('=')[0];
try {
if (cookie_name.length > 0)
doc.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
} catch(ex) {}
}
}
})(jQuery);
jQuery.cookieAllDelete(document);