Path of Cookie not working - javascript

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.

Related

Set a Javascript Cookie based on URL Params

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);

Getting multiple cookie values for same cookie different paths

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?

Java Script to MVC: Controller Variable Passing via Actionlink

Using: vs'12 Razor asp.net MVC4 Internet App Template EF Code First
My Actionlink that i am trying to manipulate
#Html.ActionLink("Download", "ShowOpenAcreageSummaryReport", new { controller = "DataToExcel" }, new { id = "AddData" })
The script to attempt this
$('#AddData').click(function (e) {
var optVal = $("#OptionsDrop").val();
var Xpro = $("#Prospects").val()
var Xcnty = $("#Countys").val()
var Xtwn = $("#TownShips").val()
var Xrng = $("#Ranges").val()
var Xsct = $("#Sections").val()
var href = "/DataToExcel/ShowLPRStandardLeaseReport/" + Xpro + Xcnty + Xtwn + Xrng + Xsct;
this.href = ""; //clears out old href for reuse
this.href = href; //changes href value to currently slected dropdown value
}
The actionResult to accept these passed values
public ActionResult ShowLPRStandardLeaseReport(string pro, string cnty, string twn, string rng, string sec)
Now i know this works with 1 variable as i have this code running on another page, however it won't work with multiple.
I have also tried adding + "/" + between the Variables, which had no effect on the outcome.
How can i change my code to be able to pass all variables??
Have you tried with GET parameters such as some-url/?param1=test&param2=test2 ? Also note that this points to the #AddData element in the click handler. If you want to change the current location, use window.location.href = 'someurl';
The ? is necessary to indicate the start of the query string parameters.
Also note that you should be encoding the values with encodeURIComponent to make sure that you are producing a valid URL.

Webpage not found javascript error

I am very new to javascript and was practicing when i came accross this error where my web browser can't find the html document when the location variable is inside the <script</script tags
<script>
<!--
var location = "Syrdsase va";
var name = "bob sixlet";
var age = 14;
document.write(name + ", " + age + location);
//-->
</script>
juste don't use location as a variable it will redirect you to a new page. change your variale's name and it will work
some reserved variables in js
http://www.quackit.com/javascript/javascript_reserved_words.cfm
There is a location object which when assigned to, changes the location of the page:
location = 'http://www.google.com'; // goes to Google homepage
Usually, to avoid confusion, it is usually referred to using window.location, but since window is simply the global object, reassigning location will make the page go to the URL that is the value of the string.
To solve the issue, simply rename the variable:
var myLocation = "Syrdsase va";
var name = "bob sixlet";
var age = 14;
document.write(name + ", " + age + myLocation);

Read a javascript cookie by name

I have set a cookie using
document.cookie =
'MYBIGCOOKIE=' + value +
'; expires=' + now.toGMTString() +
'; path=/';
Now there are between 5 and 10 cookies set on this site, is there a way to check the value ofthis cookie by name.
if (document.cookie.MYBIGCOOKIE == '1') {
alert('it is 1')
}
Use the RegExp constructor and multiple replacements to clarify the syntax:
function getCook(cookiename)
{
// Get name followed by anything except a semicolon
var cookiestring=RegExp(cookiename+"=[^;]+").exec(document.cookie);
// Return everything after the equal sign, or an empty string if the cookie name not found
return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
}
//Sample usage
var cookieValue = getCook('MYBIGCOOKIE');
Unfortunately, Javascript's cookie syntax is nowhere near as nice as that. In fact, in my opinion, it's one of the worst designed parts.
When you try to read document.cookie, you get a string containing all the cookies set. You have to parse the string, separating by the semicolon ; character. Rather than writing this yourself, there are plenty of versions available on the web. My favourite is the one at quirksmode.org. This gives you createCookie, readCookie and deleteCookie functions.
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);
}
}
}
Source: W3Schools
Edit: as #zcrar70 noted, the above code is incorrect, please see the following answer Javascript getCookie functions
You can use the following function:
function getCookiesMap(cookiesString) {
return cookiesString.split(";")
.map(function(cookieString) {
return cookieString.trim().split("=");
})
.reduce(function(acc, curr) {
acc[curr[0]] = curr[1];
return acc;
}, {});
}
When, called with document.cookie as parameter, it will return an object, with the cookies keys as keys and the cookies values.
var cookies = getCookiesMap(document.cookie);
var cookieValue = cookies["MYBIGCOOKIE"];
using jquery-cookie
I find this library helpful. 3.128 kb of pure convenience.
add script
<script src="/path/to/jquery.cookie.js"></script>
set cookie
$.cookie('name', 'value');
read cookie
$.cookie('name');
One of the shortest ways is this, however as mentioned previously it can return the wrong cookie if there's similar names (MyCookie vs AnotherMyCookie):
var regex = /MyCookie=(.[^;]*)/ig;
var match = regex.exec(document.cookie);
var value = match[1];
I use this in a chrome extension so I know the name I'm setting,
and I can make sure there won't be a duplicate, more or less.
document.cookie="MYBIGCOOKIE=1";
Your cookies would look like:
"MYBIGCOOKIE=1; PHPSESSID=d76f00dvgrtea8f917f50db8c31cce9"
first of all read all cookies:
var read_cookies = document.cookie;
then split all cookies with ";":
var split_read_cookie = read_cookies.split( ";" );
then use for loop to read each value. Into loop each value split again with "=":
for ( i = 0; i < split_read_cookie.length; i++ ){
var value = split_read_cookie[i];
value = value.split( "=" );
if( value[0] == "MYBIGCOOKIE" && value[1] == "1" ){
alert( 'it is 1' );
}
}
The point of Stack Overflow is to provide a database of good quality answers, so I am going to reference some standard source code and an article that gives examples:
http://www.codelib.net/javascript/cookies.html
Note: The code is regular-expression free for greatly enhanced efficiency.
Using the source code provided, you would use cookies like this:
makeCookie('color', 'silver');
This saves a cookie indicating that the color is silver. The cookie would expire after the current session (as soon as the user quits the browser).
makeCookie('color', 'green', { domain: 'gardens.home.com' });
This saves the color green for gardens.home.com.
makeCookie('color', 'white', { domain: '.home.com', path: '/invoices' });
makeCookie('invoiceno', '0259876', { path: '/invoices', secure: true });
saves the color white for invoices viewed anywhere at home.com. The second cookie is a secure cookie, and records an invoice number. This cookie will be sent only to pages that are viewed through secure HTTPS connections, and scripts within secure pages are the only scripts allowed to access the cookie.
One HTTP host is not allowed to store or read cookies for another HTTP host. Thus, a cookie domain must be stored with at least two periods. By default, the domain is the same as the domain of the web address which created the cookie.
The path of an HTTP cookie restricts it to certain files on the HTTP host. Some browsers use a default path of /, so the cookie will be available on the whole host. Other browsers use the whole filename. In this case, if /invoices/overdue.cgi creates a cookie, only /invoices/overdue.cgi is going to get the cookie back.
When setting paths and other parameters, they are usually based on data obtained from variables like location.href, etc. These strings are already escaped, so when the cookie is created, the cookie function does not escape these values again. Only the name and value of the cookie are escaped, so we can conveniently use arbitrary names or values. Some browsers limit the total size of a cookie, or the total number of cookies which one domain is allowed to keep.
makeCookie('rememberemail', 'yes', { expires: 7 });
makeCookie('rememberlogin', 'yes', { expires: 1 });
makeCookie('allowentergrades', 'yes', { expires: 1/24 });
these cookies would remember the user's email for 7 days, the user's login for 1 day, and allow the user to enter grades without a password for 1 hour (a twenty-fourth of a day). These time limits are obeyed even if they quit the browser, and even if they don't quit the browser. Users are free to use a different browser program, or to delete cookies. If they do this, the cookies will have no effect, regardless of the expiration date.
makeCookie('rememberlogin', 'yes', { expires: -1 });
deletes the cookie. The cookie value is superfluous, and the return value false means that deletion was successful. (A expiration of -1 is used instead of 0. If we had used 0, the cookie might be undeleted until one second past the current time. In this case we would think that deletion was unsuccessful.)
Obviously, since a cookie can be deleted in this way, a new cookie will also overwrite any value of an old cookie which has the same name, including the expiration date, etc. However, cookies for completely non-overlapping paths or domains are stored separately, and the same names do not interfere with each other. But in general, any path or domain which has access to a cookie can overwrite the cookie, no matter whether or not it changes the path or domain of the new cookie.
rmCookie('rememberlogin');
also deletes the cookie, by doing makeCookie('rememberlogin', '', { expires: -1 }). This makes the cookie code longer, but saves code for people who use it, which one might think saves more code in the long run.
I use this to read cookie:
function getCookie (key) {
let value = ''
document.cookie.split(';').forEach((e)=>{
if(e.includes(key)) {
value = e.split('=')[1]
}
})
return value
}
let name = getCookie(name)
Using string.match. Returns the cookie or null
function checkForCookie(name) {
let cookieString = document.cookie.match(name + '=[^;]+')
return cookieString ? cookieString[0] : cookieString
}
Here is an example implementation, which would make this process seamless (Borrowed from AngularJs)
var CookieReader = (function(){
var lastCookies = {};
var lastCookieString = '';
function safeGetCookie() {
try {
return document.cookie || '';
} catch (e) {
return '';
}
}
function safeDecodeURIComponent(str) {
try {
return decodeURIComponent(str);
} catch (e) {
return str;
}
}
function isUndefined(value) {
return typeof value === 'undefined';
}
return function () {
var cookieArray, cookie, i, index, name;
var currentCookieString = safeGetCookie();
if (currentCookieString !== lastCookieString) {
lastCookieString = currentCookieString;
cookieArray = lastCookieString.split('; ');
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
name = safeDecodeURIComponent(cookie.substring(0, index));
if (isUndefined(lastCookies[name])) {
lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
};
})();
This is my simple solution:
function getCookieValue(userKey){
let items = document.cookie.split(";")
for(item of items){
let [key, value] = item.split("=");
if(key === userKey)
return value;
};
return null;
}
I have come up with confusing yet very simple step after 2 hrs of concentration.
suppose a cookie 'username' is stored with a value 'John Doe'.
Then call readCookies('username'), this function (defined just below ) returns the value 'John Doe'.
function readCookies(requestedKey){
var cookies = document.cookie;
var temporaryKeyIndex=-1,temporaryKeySet=false,temporaryKey,temporaryValue;
var temporaryValueIndex = -1,previousTemporaryValueIndex=-2;
var readableCookie=[];
var a;
for(var i=0;i<cookies.length;i++){
if(cookies[i]!='='&&!temporaryKeySet){
temporaryKeyIndex++;
temporaryValueIndex++;
}
else{
temporaryKeySet = true;
if(cookies[i]==';'||i==(cookies.length-1)){
temporaryKey = cookies.slice(previousTemporaryValueIndex+2,temporaryKeyIndex+1);
if(cookies.length>temporaryValueIndex+2){
temporaryValue = cookies.slice(temporaryKeyIndex+2,temporaryValueIndex+1);
}
else{
temporaryValue = cookies.slice(-((cookies.length-1) - (temporaryKeyIndex+1)))
}
alert('tempkey: '+temporaryKey+', reqKEY: '+requestedKey);
if(requestedKey.trim()==temporaryKey.trim()){
alert(1);
return temporaryValue;
}
previousTemporaryValueIndex = temporaryValueIndex;
temporaryKeyIndex = ++temporaryValueIndex;
temporaryKeySet=false;
}
else{
temporaryValueIndex++;
}
}
}
}
Here is an API which was written to smooth over the nasty browser cookie "API"
https://github.com/jaaulde/cookies
The simplest way to read a cookie I can think is using Regexp like this:
**Replace COOKIE_NAME with the name of your cookie.
document.cookie.match(/COOKIE_NAME=([^;]*);/)[1]
How does it work?
Cookies are stored in document.cookie like this: cookieName=cookieValue;cookieName2=cookieValue2;.....
The regex searches the whole cookie string for literaly "COOKIE_NAME=" and captures anything after it that is not a semicolon until it actually finds a semicolon;
Then we use [1] to get the second item from array, which is the captured group.

Categories