Working on a local url: http://127.0.0.1:8000/qa/
Setting cookies using this JS code:
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + newSize + "; " + expires; + "path=/";
}
If I call setCookie from /qa/, I can see that the following cookie has been set:
Name=font; Value=12px; Domain=127.0.0.1; Path=/qa
If I subsequently call setCookie from a different url (eg /qa/profile), I see that a second cookie has been created as follows:
Name=font; Value=12px; Domain=127.0.0.1; Path=/qa
Name=font; Value=18px; Domain=127.0.0.1; Path=/qa/profile
What I want is for any call to setCoookie to override the previous value of the initial cookie so that there is only ever one cookie with name="font" and that its value always reflects the last set value. I thought that specifying "path=/"; in my jquery function would do the trick. But it hasn't. What am I doing wrong?
Related
I use this code to change the cookie value in php, or set it if it does not exist yet:
setcookie('maintenance_site_contact_failed', '1', time()+3600, '/', 'entwicklung');
And I am using this code to set a cookie in javascript:
setCookie('maintenance_site_contact_failed', '0', 1);
function setCookie(name,value,days)
{
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
But as you can see in the following screenshot the cookie is created a second time instead of changing the existing one, but the duplicate has a dot in the domain name.
Why is there a dot and why is the cookie created twice?
What I try:
If a user sends my form and the validation fails on serverside, then
I am setting the cookie maintenance_site_contact_failed in the PHP script to 1 so that the client knows that an error happened.
The javascript then checks the value of the cookie, and if the cookie value is 1 then it shows an error and resets the cookie value to 0.
Looks like your cookie is only available to different subdomains because in the php equivalent you're assigning a value for the domain parameter.
Try to do the same inside the Javascript setCookie function:
document.cookie = name + "=" + (value || "") + expires + "; path=/; domain=entwicklung";
I'm curious if someone can help a very new Javascript user make sense of how to set a cookie, based on specific URL parameters. I see that pulling the data from the URL using JavaScript is covered in this post:
How can I get query string values in JavaScript?
But I can not figure out how to pull that information into a cookie to store the information throughout a users session on the site.
I would like to grab 3 main URL parameters:
utm_source
utm_medium
utm_campaign
And then store them in a cookie in Google Tag Manager using Javascript.
I can not wrap my head around making this happen. Any help would be greatly appreciated. Sorry I dont have much code to show for reference, but I have been experimenting ( and failing ) for hours now.
Thank you so much for any insight on this.
Cheer,
Melissa
Edit:
Sorry...I wasn't expecting someone to write it for me, I just didn't think my very failed attempts would help anyone see what I was trying to do so I just explained.
Here is my code as of now, and I know it's sort of working. I'm editing a previous cookie that stores the site referrer in a cookie. So as it stands right now, the cookie stores the referrer on the first pageview, then if you go to a different page it will show the {{utm_medium}} and continue to show that throughout the visit. I would like for it to not show the referrer, but output a cookie that displays {{utm_source}} | {{utm_medium}} | {{utm_campaign}} if that's even possible...
Thank you again for any help or pointers or articles. I really appreciate it.
<script> //get referrer info and shorten it
var ref = {{Referrer}}
function extractDomain(url) {
var domain;
//find & remove protocol (http, ftp, etc.) and get domain
if (url.indexOf("://") > -1) {
domain = url.split('/')[2];
} else {
domain = url.split('/')[0];
}
//find & remove port number
domain = domain.split(':')[0];
return domain;
}
ref = extractDomain(ref);
//create cookie
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=/";
}
var cookie = "";
//check if UTMs are present and set cookie content to the source utm
if ({{utm_source}}) {
createCookie("utmsource", cookie + {{utm_source}}, 1000)
} else if ({{utm_medium}}) {
createCookie("utmsource", cookie + "Email", 1000)
//check if referrer is present and set cookie content to the referrer
} else if ({{utm_campaign}}) {
createCookie("utmsource", cookie + "{{utm_campaign}}", 1000)
} else if {
createCookie("utmsource", cookie + "Email", 1000)
};
</script>
When you use cookie + something, you're not updating the cookie string. So each time you do this, you're just concatenating with the original, empty value of this string. Instead of calling setcookie multiple times, update the cookie string as you test the different variables, then call setcookie at the end with the combined value.
You shouldn't use else if between each test, since that will only add the second variable to the cookie if the first variable didn't exist. But you want all the variables put into the cookie.
var cookie = "";
if ({{utm_source}}) {
cookie += {{utm_source}};
}
if ({{utm_medium}}) {
cookie += ' | ' + {{utm_medium}};
} else {
cookie += ' | Email';
}
if ({{utm_campaign}}) {
cookie += ' | ' + {{utm_campaign}};
} else {
cookie += ' | Email';
}
setcookie('utm_source', cookie, 1000);
I want to create a cookie to store a class so I can use this through the whole site. I checked the cookies, and the cookie is created. The problem is when the cookie is set on another page the path is /url-page en not /
jQuery(document).ready(function($) {
values = $.map($('select option'), function(e) { return e.value; });
$('#color-select').on('change', function() {
$("body").removeClass(values.join(" ")).addClass( ("" + $('#color-select').val()) );
var foobar =("" + $('#color-select').val());
document.cookie = "gsscookie=" + foobar, "expires=;domain=;path=/";
})
});
I'm working on a local dev environment with the url plastic.dev.local. What am I doing wrong?
The value that gets assigned to document.cookie should be a single string, with a semicolon after the "key=value" assignment, and then semicolons between each property that you're setting on the cookie. The way you're doing it, with the comma after the first string, makes it so the second string is basically ignored. If you change it to document.cookie = "gsscookie=" + foobar + ";expires=;domain=;path=/";, it should work.
I have a task which is compare up to five products from the product list. For that
I have followed following steps:
step 1:
set onclick event when we click add to compare button of each product. In this event I have set cookie by javascript using this code.
// cookie is set by array because of we have to store 1 to 5 products
var comparearray = [productid];
document.cookie = "compareitem" + "=" + comparearray;
It is successfully set the cookie value which holds product id of those are selected to compare.
Step 2: In my PHP file I have tried to retrieve this cookie value.BY,
$cookie_val = $_COOKIE['compareitem '];
But it is not worked. I don't know this kind of concept is worth. If know, give me the instructions how to solve my problem. Thanks in advance.
Since it may be problem with path I suggest to set/get cookie with extended way:
document.cookie="foo=bar; path=/;"
or you can use this function:
function setCookie (name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
Since some people are writing that you can't use cookies set with JS in PHP, I'm going to answer that question now.
Please try to use a cookieSet and cookieGet function, you can use the one from this answer:
How do I create and read a value from cookie?
var createCookie = function(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
Note the last parameter which is written into the cookie.. the path-param is set to '/', so the root location! Use a php script in the root location, so that both use the root location and not some other location.
Next please try to stringify the array with JSON.
var cookiedata = JSON.stringify(comparearray);
Then you should be able to get the cookie with PHP and parse the JSON to get the array back.
I have set a cookie with document.cookie. The content settings in Google Chrome is showing the cookie. However, document.cookie is displaying as a blank string when printed. Why is this happening?
Here is my code
function setCookie(name,value,lifeTime,path,domain,secure){//lifetime in hours
{
var c_ = name +'='+escape(value)+'; ';
var life = new Date();
lifeTime<1&&lifeTime>0?life.setMinutes(life.getMinutes()+lifeTime*60):life.setHours(life.getHours()+lifeTime);
life = life.toUTCString();
c_+='expires='+life+"; ";
c_+= 'domain='+domain+'; ';
c_ += 'secure=secure; ';//secure
c_ += 'path='+path;
document.cookie = c_;
alert(document.cookie);
/*Just splitted the code instead of c = 'name='+value+'expires ='+life etc*/
}
A possible problem with this function is, it always sets a secure cookie. So, if you've requested/opened the page with HTTP not HTTPS protocol, the secure cookie won't be exposed.