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.
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.
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
I have a question about cookies in cakephp. I create a cookies in cakephp view successfully, and I wrote a javascript function to delete that cookies if the page reloads, and that function is successfully deleted.
But after that cookies deleted, the same cookies cannot create anymore. Why does this happen?
This is my code that I have used to create that cookies :
$isiCookies=$awb['Awb']['id'].'^'.$awb['Awb']['awb_number'].'^'.$companies[$awb['Contract']['company_id']].'^'.$awb['Address']['address'].'^'.$types[$awb['ContractDetail']['content_type_id']].'^'.$awb['Awb']['colie'].'^'.$kilo.'^'.$manifestDetails[$awb['Awb']['id']];
if(!isset($_COOKIE['manifest_courier']))
{
setcookie("manifest_courier", $isiCookies, $date_of_expiry, "/");
}
else
{
setcookie("manifest_courier", rawurldecode($_COOKIE['manifest_courier']).'*'.$isiCookies, $date_of_expiry, "/" );
}
And this is the javascript function that I have used to deleted the cookies :
$(window).unload(function() {
Cookies.erase('manifest_courier');
});
Please tell me why the cookies are not created if the page reload. Thanks for your help.
You don't need to do everything in views.
First off, make sure the Cookie component is included in the controller.
var $components = array('Cookie');
Then, in your function,
$isiCookies = $awb['Awb']['id'].'^'.$awb['Awb']['awb_number'].'^'.$companies[$awb['Contract']['company_id']].'^'.$awb['Address']['address'].'^'.$types[$awb['ContractDetail']['content_type_id']].'^'.$awb['Awb']['colie'].'^'.$kilo.'^'.$manifestDetails[$awb['Awb']['id']];
if($this->Session->check('manifest_courier'))
{
$this->Cookie->write('manifest_courier',$isiCookies,false,$date_of_expiry);
}else{
$this->Cookie->write('manifest_courier',rawurldecode($_COOKIE['manifest_courier']).'*'.$isiCookies,false,$date_of_expiry);
}
In view, use that Js to delete the cookie if it still exists after refresh.
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");
In my site i have a welcome animation (created with jquery) which runs when any one opens my website (www.mysite.com). Then the same user going to anther page in my site for example www.mysite.com/about then click back to home (www.mysite.com) the animation again shows up. How can i restrict this ?
Share some logic like putting a session or settimeout or something like that.
This is how you could do it using jquery cookie plugin:
http://jsfiddle.net/lollero/2nYBV/ ( or http://jsfiddle.net/lollero/2nYBV/show/ )
You might want to change the way cookie expires. That info can be found in the plugin page. The way I did it, it expires after every browser session.
jQuery:
You could just as easily reverse this to hide, if the cookie is set. 1. Set cookie 2. if statement to trigger hide, if cookie is set.
// If "welcome" cookie is not set...
if ( $.cookie('welcome') === null ) {
// Show welcome text.
$('#welcome').show();
// Set the "welcome" cookie, so that the
// welcome text will not be shown after this.
$.cookie('welcome', true );
}
CSS:
#welcome {
display: none;
}
HTML:
<div id="welcome">Welcome</div>
See the following link for information on how to setup cookies using JQuery:
How do I set/unset cookie with jQuery?
Everytime you load the homepage, you can check if the cookie is set using an if-statement. If the cookie is not set, run the animation.
Within the animation-script; make sure that you set the cookie so that the script won't run again while the cookie is active.
You can set cookie either on server side or either client side
And check whether the cookie is set or not if cookie is set then dont show welcome box otherwise show the welcome box...
In php you can set session cookie using setcookie function please see below link:-
http://php.net/manual/en/function.setcookie.php
Place timer with flag then redirect to main page in your site.
setTimeout(function() {window.location.href = "/NewPage.php";}, 2000);
You can use a session to handle this.
An example:
<?php
$_SESSION['new'] = true;
?>
At first visit main page - define a flag in cookies, and at each visit of page check this flag