I'm using Facebook Php SDK v3.22 which I have JavaScript set me a cookie that is read in Php
For some reason when I use an if statement like so:
if($_COOKIE['anything'] == 'some_data'){
//do something
}
My canvas page redirects to a blank page with no error caught upon logout
I see in my page info that there are no cookies in the framed canvas page but I'm a little confused as I'm using server side Php to read the cookies and how this can result in Facebook redirecting to a blank page when ever I use an if cookie statement, it's sorcery!
I'm setting my cookies with JavaScript like so:
<script language="JavaScript" type="text/javascript">
<!--
if (self != top) {;
var onsite = 'true'; document.cookie = 'domainname.com' + "=" + onsite;
}else{
var onsite = 'false'; document.cookie = 'domainname.com' + "=" + onsite;
}
-->
</script>
Use the following javascript on your Page:
<script type="text/javascript">
// Set cookie function
function setCookie(c_name,value,exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
// Set the cookie
var onsite = 'false',
domain = 'domainname.com';
if (self != top) {
onsite = 'true';
}
setCookie(domain, onsite);
</script>
And your PHP script will look like this:
<?php
// Test cookie
$domain = 'domainname.com';
if (isset($_COOKIE[$domain])) {
if ($_COOKIE[$domain] == 'true') {
// domainname.com is equal to 'true'
} else {
// domainname.com is NOT equal to 'true'
}
} else {
// cookie is not set yet
}
?>
*Note if you are trying to read the cookie before it's set, it wont really work.
Related
I've set a cookie using PHP,
setcookie("redirect", $this->currentPage(), time() + 31536000);
but I want to retrieve the value of this cookie using javascript when a certain link is clicked. How can I do that?
Yes its possible.
Try this to read 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);
}
}
}
// get cookie foo
var foo = getCookie('foo');
Try this to set a cookie:
/**
* Sets a cookie
*/
function setCookie(c_name,value,exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
// set a cookie 'foo=bar' for 3 days
setCookie('foo', 'bar', 3);
Cookies are not PHP specific they are browser specific and they can be placed both from PHP and Javascript. For an easy solution, you can look into jQuery's Cookie plugin
Here's another take that attempts to be easier to understand.
Also, since cookies are encoded (both keys and values), you will want to decode them both.
var getCookie = function(name) {
var thisCookie,
keyValuePair,
key,
value,
cookies = document.cookie.split('; ') ;
for ( var i=0 ; i<cookies.length ; i++ ) {
thisCookie = cookies[i] ;
keyValuePair = thisCookie.split('=') ;
key = decodeURIComponent(keyValuePair[0]) ;
if ( key === name ) {
value = keyValuePair[1] ;
return (value != null) ? decodeURIComponent(value) : null;
}
}
}
Regarding the part about getting the cookie on a link click, you would call this function in an event handler.
Let's assume that you know how to get the link in question in JavaScript. Here's one way to get the first link in the document:
var link = document.querySelector('A') ;
In any case, once you have your link, here is how to get the value when the link is clicked:
var getCookieOnLinkClick = function() {
var cookieValue = getCookie('cookieName') ;
console.log('Cookie value is ', cookieValue) ;
}
link.addEventListener('click', getCookieOnLinkClick) ;
(Of course, most links will load a new page, so you won't have much time to do anything with the cookie value once you get it.)
Wrong concept. Cookies are stored in browsers. PHP gets/sets browser cookies through HTTP requests and responses. So both PHP and browser JS can manipulate the same cookies.
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
$(document).ready(function(){
alert(getCookie('foo'));
setCookie('foo','test'); //just setting a cookie on page load
$('#bing').click(function(){
$('#frm1').submit();
});
});
HTML side(foo.phtml)
Go
<form id="frm1" method="POST" action="/somecontroller/someaction">
<input type="hidden" name="foo_post" value="this is from post" />
</form>
//server side
public function someactionAction(){
$_COOKIE['foo'] = $this->_request->getPost('foo_post');
$this->_redirect('/somecontroller/foo');
}
My problem is on the very first load of a page the alert returns null since cookie is not set and if i refresh again,ill get an alert "test" but if i click on the anchor tag a form submit will occur and the cookie value is rewritten as "this is from post",so obviously after the action back to the page ill get an alert of "this is from post" ,BUT im still getting an alert "test" ,The cookie value is not getting rewritten
In my mozilla cookie console there are two cookies with the name foo with values "test" and "this is from post"
"there are two cookies with the name foo"
If the name is identical, the domains must be different. Set both cookies using the same domain. Be aware that example.net is different from www.example.net or .example.net.
i've a php page with a form in which i have a checkbox that user can check to select to remember field in browser next login. i'm using that code:
if(rememberCheck.checked==true){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var cod_value=escape(codice.value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie="cod=" + cod_value+";log="+login.value;
}
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);
}
}
}
function checkCookie(){
var cod=getCookie("cod");
var username = getCookie("login");
if (username!=null && username!="" && cod!=null && cod!=""){
var usn = document.getElementsByName('usn')[0];
var codice = document.getElementsByName('codice')[0];
usn.value=username;
codice.value=cod;
}
}
The problem is that when i read cookie, it read PHPSESSID=XXXXXX, and not what i write. What can i do? can you help me?
You can do it with php too.
on login if user checked "remember me", then on php
you can do like
<?php if( isset($_POST['rem_me']) &&
$_POST['rem_me']=='on' ) {
setcookie ("code", $value, time()+(3600*24*30*12)); //set your cookie } ?>
if is there any reason why you want to do it with javascript only?
<?php
if( isset($_POST['rem_me'])){
if($_POST['rem_me']=='on'){
setcookie ("remember", $value, time()+360000);
}
}
?>
why not use jquery $post to set PHP cookies on the server instead, they are easier to work with than js cookies
I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
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==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/
I need to have a pop-up window displayed when a page loads. What's happening is this. After an order is placed the user is redirected to their index page (main log-in page for the account) when they are redirected to the index page, I need a pop-up window to display on the page load that says something like "Your order for $variable has been saved". The $variable is defined on the previous page (where they are coming from) and I need that to carry over so I can display it in the pop-up box. Then once they click on "Ok" in the pop-up box, they are at the main page like always.
I have used a java popup box before on this project, but I am unsure of how to do one with these requirements. If there are any other/better ways to do this I am open to ideas. The layout of how this needs to work is below:
Client is logged into their account -> Order.php Page (Place an order) -> redirected to their member-index.php page (Pop-up needs to load on page load, and only when it comes from the order.php page)
Thanks!
Well from what I understand this would be the best match for you.
On previous page save a cookie (source http://www.quirksmode.org/js/cookies.html).
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
createookie("prevData", prevData, 30);
Then on the page you want the popup to appear (I suggest using an alert) (Note: you need the cookie code available on this page as well):
var prevData = readCookie("prevData");
if(prevData != null){
alert("Your order for " + prevData + " has been saved");
eraseCookie("prevData");
}
this could be in <body onLoad="code"> or simply a script in the header or anywhere really.
You can't force a popup page to open upon page load; browsers won't do that anymore. You can create a "fake" popup window by just positioning an element in the middle of the screen and decorating it so that it looks kind-of like a window. Various JavaScript libraries provide such "dialog" facilities.
`
function showpopup() {
var findString = /order.php/gi;
var referringURL = document.referrer;
var data = getQuerystring('variable');
if(referringURL.match(findString)) {
var windowprops = "left=50,top=50,width=500,height=500";
var preview = window.open("http://google.com", "preview", windowprops);
preview.document.write(data);
} else {
alert("Not order.php "+data);
}
}
function getQuerystring(key, default_) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
</script>
</head>
<body onload="showpopup()">
`
I assume you mean javascript. You may want to do this
<body onLoad="popup()">
Any code in the "onLoad" event should fire once the html is loaded.
If you are using Jquery, it should look like this
$("document").ready(function() {
popup();
});
You can pass your variable into the popup function.