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.
Related
Though I have set the cookie using setcookie, why does it skip to the else part during the first time of execution/ first visit?
<?php
setcookie("dan", "Sony", time()+60);
if(isset($_COOKIE['dan']))
{
echo "Set";
}
else
{
echo "Not yet!";
}
?>
P.S: I know it is a naive question and gets downvoted but I don't find a better forum than StackOverflow.
setcookie() merely arranges for the HTML headers emitted by the PHP script to contain the necessary "Set-Cookie:" header. The browser responds by storing the cookie and then regurgitating it on the next request to the site.
setcookie() does not set any variables inside the currently-executing script, which is why you're not seeing anything the first time through.
You can't get value from $_COOKIE in the same request you do setcookie, you could get it begin from the next request.
The first time you only tell the browser to set the cookie, at the time, there is no cookie data in the request header (which could get from $_COOKIE).
Set your cookies with javascript.
function createCookie(name,days,value) {
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) { //cookie reader function
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) { //cookie eraser function
createCookie(name,"",-1);
}
createCookie("test", 1, 1);
var mycookie= readCookie("test");
alert(mycookie);
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.
I am using this code in my js file for redirect
setTimeout('top.location=\'http://google.com/?123\';', 1000);
Problem is my js file execute many time but i want to add some cookie code in js file so that my visitor dont redirect again and again. so what will be cookie code which execute this js file only once unless i change cookie manually
Create your code with this function in mind, using these steps in order. You can check your js reference for how to do each of these steps. I hope this points you in the right direction.
Check for an existing cookie.
If you find the cookie, do not redirect, otherwise, redirect. (This is where your existing line would come in.)
Set a cookie with a timeout value based on how often you want them to redirect.
Not tested
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;
}
if(readCookie('redirected')!=true)
{
createCookie('redirected',true,0); // cookie will be trashed after the browser closed.
setTimeout('top.location=\'http://google.com/?123\';', 1000);
}
Read here.
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
Yes, I KNOW about Google Analytics. We use it for our overall site metrics, and I know we can track individual links. However, we needed a tracking solution for very specific links and we need that tracking data available to our web application in real time, so I wrote my own solution:
jQuery:
$.fn.track = function () {
var source, url, name, ref, $this;
$this = $(this);
if (window.location.search.substring(1) != '') {
source = window.location.pathname + "?" + window.location.search.substring(1);
} else {
source = window.location.pathname;
}
url = jQuery.URLEncode($this.attr('href'));
name = $this.attr('name');
ref = jQuery.URLEncode(source);
$this.live('click', function (click) {
click.preventDefault();
$.post('/lib/track.php', {
url: url,
name: name,
ref: ref
}, function () { window.location = $this.attr('href'); });
});
};
... using the jQuery URLEncode plugin (http://www.digitalbart.com/jquery-and-urlencode/).
Now, this code works fine with my PHP backend and on my machine, but it doesn't seem to work reliably for everyone else. Sometimes the parameters passed in via jQuery are NOT passed in, resulting in a record in the database with no name, url or ref.
For the life of me, I can't figure out why this might be happening; I know the $.post is triggering, since there are records in the database (in the PHP, I also record the IP of the request along with the timestamp), but in many cases the PHP script is receiving blank $_POST variables from jQuery.
I've tested it live on every browser I have access to at my workplace, and all of them work fine for me; however, about 75% of all the records created (not by my computers) come through as blank (most of them are using the same browsers I am).
Why could this be happening?
I think, in the end, my problem ended up being that it was taking too long for the request to be parsed by jQuery, and I'm pretty adamant about not wanting to make the links "dependent" on javascript (either that they wouldn't work without it or that the user would have to wait for the tracking request to complete before they hit the new page).
After browsing many other solutions online--borrowing from some and being inspired by others--I arrived at the solution below in native javascript:
if (document.getElementsByClassName === undefined) { // get elements by class name, adjusted for IE's incompetence
document.getElementsByClassName = function(className) {
var hasClassName, allElements, results, element;
hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
allElements = document.getElementsByTagName("*");
results = [];
for (var i = 0; (element = allElements[i]) !== null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass)) {
results.push(element);
}
}
return results;
};
}
function addTracker(obj, type, fn) { // adds a tracker to the page, like $('xxx').event
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
} else if (obj.addEventListener) {
obj['e' + type + fn] = fn;
obj[type + fn] = function() {
obj['e' + type + fn]( window.event );
};
obj.attachEvent('on' + type, obj[type + fn]);
}
}
function save_click(passed_object) { // this function records a click
var now, then, path, encoded, to, from, name, img;
now = new Date();
path = '/lib/click.php';
from = (window.decode) ? window.decodeURI(document.URL) : document.URL;
to = (window.decodeURI) ? window.decodeURI(passed_object.href) : passed_object.href;
name = (passed_object.name && passed_object.name != '') ? passed_object.name : '[No Name]';
// timestamp the path!
path += '?timestamp=' + now.getTime();
path += '&to=' + escape(to) + '&from=' + escape(from) + '&name=' + name; // compile the path with the recorded information
img = new Image();
img.src = path; // when we call the image, we poll the php page; genius!
while (now.getTime() < then) {
now = new Date(); // resets the timer for subsequent clicks
}
}
function get_targeted_links(target) { // finds targeted elements and wires them up with an event handler
var links, link;
if (document.getElementsByClassName) {
links = document.getElementsByClassName(target);
for (var i = 0; i < links.length; i++) {
link = links[i];
if (link.href) {
addTracker(links[i], 'mousedown', save_click(links[i]));
}
}
}
}
addTracker(window, 'load', get_targeted_links('trackit'));
... which seems to be much snappier than the jQuery plugin I had written above, and so far has been fast enough to track all the requests I've thrown at it.
Hope that helps someone else!
These "clicks" might be coming from bots, or someone with JS disabled. If you the links clicked must be tracked why don't you consider JS only links, ie. put URL in a different attr other than href, then use your click handler to process it, add referral check in your track.php
Also have you checked if all elements are links?