Hi I am just a beginner and I am setting a Cookie to remember a user. When I have tested it, with just opening the file in my Browser(Safari) it worked fine, but after uploading it to my server (xxxxxx.bplaced.net) it is not working anymore. Here is my Code:
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 + ";domain=xxxx.bplaced.net;path=/";
}
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
setCookie('justacookie','testcookie',7);
Can anyone help me?
Client-Side setting and getting cookie:
//set cookies
document.cookie = "userId=jkadfa08da7f8f6a7fa";
//get cookies
function getCookieValue(name) {
var cookies = document.cookie;
var cookiesArray = cookies.split(';');
var findCookie = cookiesArray.find(c => c.includes(name));
var cookieSplit = findCookie.split('=');
//cookieSplit[0] === name (key)
return cookieSplit[1];
}
Server-Side(Node.js) setting and getting cookies.
first, install the cookie-parser library.
add to you server application the middleware like that:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
then you will can get and set every API the cookies like that:
//get cookie
req.cookies['cookieName'];
//set cookie
res.cookie("userId","jkadfa08da7f8f6a7fa")
if you mean that you want to send them to server by request:
cookies are sub key in header, and every request you can send headers.
axios.post('url', {"body":data}, {
headers: {
'Content-Type': 'application/json',
'Cookie': yourcookie
}
}
)
I'm definitely new to Javascript, but I need to implement a tag within GTM to update 2 cookie values to 6 months for any unique user after the are loaded on the page.
I have the following script to alter the expiration date:
<script>
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2)
return parts.pop().split(";").shift();
}
var date = new Date();
date.setTime(date.getTime()+(365*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
console.log("expires: " + expires);
var cookieName = "CookieA";
var OABCcookieName = "CookieB";
function updateCookieExpiration() {
var cookie = getCookie(cookieName);
document.cookie = cookieName + "=" + cookie + expires + ";path=/; Samesite=Lax;" //domain=" + domain + ";";
var OABCcookie = getCookie(OABCcookieName);
document.cookie = OABCcookieName + "=" + OABCcookie + expires + ";path=/; Samesite=Lax;" //domain=" + domain + ";";
}
</script>
My question is, if I add the following script, update 365 to 180, and call the updateCookieExpiration() function - won't the function be called on every page and cause the cookie expiration to always reset to 6 months?
If so, is there additional logic that I need to add to make sure the cookie expiration hasn't already been reset for a unique visitor, to avoid the scenario described?
Any help troubleshooting would be great and very appreciated!
You could add a condition check if the Cookie name already exist:
// You may prefer using max-age here
const sixMonthMaxAge = 60 * 60 * 24 * 180;
var newCookieName = "CookieA";
function updateCookieExpiration() {
const cookie = getCookie(cookieName);
// If cookie doesn't exist
if(!cookie) {
document.cookie = cookieName + "=" + cookie + ";" + "max-age=" sixMonthMaxAge + ";"
}
}
Using js-cookie library
Using library that abstract Cookie management can be a good idea, even more if you have to manager multiple cookies.
import Cookies from 'js-cookie'
const sixMonthMaxAge = 180; // You can provide the max-age in days
var newCookieName = "CookieA";
function updateCookieExpiration() {
const cookie = Cookies.get(cookieName);
if(!cookie) {
Cookie.set(cookieName, 'your_value', { expires: sixMonthMaxAge })
}
}
Cookies.set('foo', 'bar')
Link to code to test: https://jsbin.com/modocelume/edit?js,console
One of my cookies are always coming up null. The rest read fine. In the actual application, it's meant to read URL parameters. In that scenario, I can actually change which one is null, but it's always at least one!
I can see the cookie is set in the developer tools, it's not HTTP Only, and the expiration is fine.
Anyone have any experience with this?
var urlParams = [
'utm_source',
'utm_medium',
'utm_campaign',
'utm_term',
'utm_content'
];
function createCookie(name, value, days, domain) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = '; expires=' + date.toGMTString();
} else {
var expires = '';
}
if (domain) {
var domain = '; domain=' + domain;
}
document.cookie = name + '=' + value + expires + domain + '; path=/';
}
function readCookie(name) {
var name = name + '=',
fields = document.cookie.split(';');
for(var i=0; i < fields.length; i++) {
var field = fields[i];
while (field.charAt(0)==' ') {
field = field.substring(1, field.length);
if (field.indexOf(name) == 0) {
return field.substring(name.length, field.length);
}
}
}
return null;
}
urlParams.forEach(function(param) {
createCookie(param, param, 365, '');
});
urlParams.forEach(function(param) {
console.log(readCookie(param));
});
I expect the output for readCookie('utm_source') to be utm_source, but the output is null.
Thanks for your help!
For some reason, your utm_source field name did not have an empty space in front of it, so your while (field.charAt(0) === ' ') didn't fire for it. I changed it to below code and it seems to be working fine now:
function readCookie(name) {
var name = name + '=',
fields = document.cookie.split(';');
for(var i=0; i < fields.length; i++) {
var field = fields[i].trim();
if (field.indexOf(name) == 0) {
return field.substring(name.length, field.length);
}
}
return null;
}
I'm trying to set a cookie using javascript so it expires when the browser is closed.
I have the following function to do that:
function createCookie(value,days) {
var name = "name";
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
var cookie = name + "=" + value + expires + "; path=/";
document.cookie = cookie;
}
I tried many ways found here and there on the web like setting the date to "", setting it to yesterday (in that case the cookie is not even added) and omitting "expires" completly. I tried on Firefox and Chrome checking that every process was stopped before opening again, but the cookie is alway there.
What am I missing?
I am using this function for my self. It will work for you i gess :)
function createCookie(name, value, expiresInX_days, path) {
var a = new Date;
var expires = expiresInX_days || 1;
a.setTime(Date.now() + (1000 * 60 * 60 * 24 * expires));
var pt = path ? " ; path=" + path + ";" : ";";
return (document.cookie = name + "=" + value + ";" + "expires=" + a.toUTCString() + pt) ? !0 : !1;
}
If you want to delete your cookie, you can use this:
function rmCookie(cookieName){
var a = new Date;
a.setTime(0);
return (document.cookie = cookieName + "=;" + a.toUTCString()) ? !0 : !1;
}
If you want get your cookie clean,
function getMyFuckingCookie(cookieName){
var a = document.cookie.replace(/; /g, ";").split(";"),
b = a.length,
c = {},
nm = cookieName || !1;
while (b--) {
var d = a[b].split(/=(.+)/);
c[d[0]] = d[1];
}
return (nm) ? c[nm] : c;
}
If the &view-all parameter does NOT exist in the URL I need to add it to the end of the URL along with a value. If it DOES exist then I need to be able to just change the value without creating a new URL because it might, or might not, have other parameters before it.
I found this function but I can't get it to work: https://stackoverflow.com/a/10997390/837705
Here is the code I have using the function above (which I can't get to work): http://jsfiddle.net/Draven/tTPYL/4/
I know how to append the parameter and value already:
<div onclick="javascript: window.location.assign(window.location.href+='&view-all=Yes');">Blah Blah</div>
More Info:
If the URL is http://www.domain.com/index.php?action=my_action then the default "&view-all" value would be "Yes" so the URL they would be directed to when they click the button is http://www.domain.com/index.php?action=my_action&view-all=Yes.
If the URL is http://www.domain.com/index.php?action=my_action&view-all=Yes then when they click the button it would change to http://www.domain.com/index.php?action=my_action&view-all=No
EDIT: Please give me examples. I don't know alot of JS, and I just can't think of a way to do it in PHP.
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName + "="));
var suffix = url.substring(url.indexOf(paramName + "="));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
window.location.href = url + hash;
}
Call the function above in your onclick event.
Why parse the query string yourself when you can let the browser do it for you?
function changeQS(key, value) {
let urlParams = new URLSearchParams(location.search.substr(1));
urlParams.set(key, value);
location.search = urlParams.toString();
}
All the preivous solution doesn't take in account posibility of the substring in parameter. For example http://xyz?ca=1&a=2 wouldn't select parameter a but ca. Here is function which goes through parameters and checks them.
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf("?") >= 0)
{
var params = url.substring(url.indexOf("?") + 1).split("&");
var paramFound = false;
params.forEach(function(param, index) {
var p = param.split("=");
if (p[0] == paramName) {
params[index] = paramName + "=" + paramValue;
paramFound = true;
}
});
if (!paramFound) params.push(paramName + "=" + paramValue);
url = url.substring(0, url.indexOf("?")+1) + params.join("&");
}
else
url += "?" + paramName + "=" + paramValue;
window.location.href = url + hash;
}
I had a similar situation where I wanted to replace a URL query parameter. However, I only had one param, and I could simply replace it:
window.location.search = '?filter=' + my_filter_value
The location.search property allows you to get or set the query portion of a URL.
To do it in PHP: You have a couple of parameters to view your page, lets say action and view-all. You will (probably) access these already with $action = $_GET['action'] or whatever, maybe setting a default value.
Then you decide depending on that if you want to swich a variable like $viewAll = $viewAll == 'Yes' ? 'No' : 'Yes'.
And in the end you just build the url with these values again like
$clickUrl = $_SERVER['PHP_SELF'] . '?action=' . $action . '&view-all=' . $viewAll;
And thats it.
So you depend on the page status and not the users url (because maybe you decide later that $viewAll is Yes as default or whatever).
Some simple ideas to get you going:
In PHP you can do it like this:
if (!array_key_exists(explode('=', explode('&', $_GET))) {
/* add the view-all bit here */
}
In javascript:
if(!location.search.match(/view\-all=/)) {
location.href = location.href + '&view-all=Yes';
}
though i take the url from an input, it's easy adjustable to the real url.
var value = 0;
$('#check').click(function()
{
var originalURL = $('#test').val();
var exists = originalURL.indexOf('&view-all');
if(exists === -1)
{
$('#test').val(originalURL + '&view-all=value' + value++);
}
else
{
$('#test').val(originalURL.substr(0, exists + 15) + value++);
}
});
http://jsfiddle.net/8YPh9/31/
Here's a way of accomplishing this. It takes the param name and param value, and an optional 'clear'. If you supply clear=true, it will remove all other params and just leave the newly added one - in other cases, it will either replace the original with the new, or add it if it's not present in the querystring.
This is modified from the original top answer as that one broke if it replaced anything but the last value. This will work for any value, and preserve the existing order.
function setGetParameter(paramName, paramValue, clear)
{
clear = typeof clear !== 'undefined' ? clear : false;
var url = window.location.href;
var queryString = location.search.substring(1);
var newQueryString = "";
if (clear)
{
newQueryString = paramName + "=" + paramValue;
}
else if (url.indexOf(paramName + "=") >= 0)
{
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
if(newQueryString.length > 0) {newQueryString += "&";}
if(decode(key[0]) == paramName)
{
newQueryString += key[0] + "=" + encodeURIComponent(paramValue);;
}
else
{
newQueryString += key[0] + "=" + key[1];
}
}
}
}
else
{
if (url.indexOf("?") < 0)
newQueryString = "?" + paramName + "=" + paramValue;
else
newQueryString = queryString + "&" + paramName + "=" + paramValue;
}
window.location.href = window.location.href.split('?')[0] + "?" + newQueryString;
}
i would suggest a little change to #Lajos's answer... in my particular situation i could potentially have a hash as part of the url, which will cause problems for parsing the parameter that we're inserting with this method after the redirect.
function setGetParameter(paramName, paramValue) {
var url = window.location.href.replace(window.location.hash, '');
if (url.indexOf(paramName + "=") >= 0) {
var prefix = url.substring(0, url.indexOf(paramName));
var suffix = url.substring(url.indexOf(paramName));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}else {
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
url += window.location.hash;
window.location.href = url;
}
This is my sample code for rebuild url query string with JS
//function get current parameters
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
};
//build a new parameters
var param1 = $.urlParam('param1');
var param2 = $.urlParam('param2');
//check and create an array to save parameters
var params = {};
if (param1 != null) {
params['param1'] = param1;
}
if (order != null) {
params['param2'] = param2;
}
//build a new url with new parameters using jQuery param
window.location.href = window.location.origin + window.location.pathname + '?' + $.param(params);
I used JQUERY param: http://api.jquery.com/jquery.param/ to create a new url with new parameters.
I need help to adjust my script below or to find a script that could be used on my wordpress site to grab the url suffix parameters from a forward url, then to be added at the button click url for tracking the proper forward ads id.
REASON: parameters are used for advertisement tracking to find out from which ad the user has been forward, even if the user hops from optin page to the sales page by using button click.
Here the goal to reach:
1. An FB ad points to an optin page with tracking code: https://ownsite.com/optin-page/?tid=fbad1
2. At the optin-page there is a button with a setup URL to forward to the sales page, but if clicked then only the URL is forward, but the parameter "?tid=fbad1" is missing.
3. The auto-forward script below (which is working properly) can be used to change for button click forward, but has a limitation as it grab only "tid" parameters instead also utm parameters.
Therefore a script code shall be implemented to establish click buttons (also to style them or use images instead) and while clicking the button to forward to a different sales page with grabbing the suffix parameter form the current optin-page to forward then to sales-page https://ownsite.com/sales-page/?tid=fbad1 also including UTM parameters
Currently, I could have solved this by using an auto-redirect script, but
A.) I do not want to use an autoredirect at this page. Better is an event click button used to let the user himself click to forward with the URL parameter included.
B.) The tracking ID parameter in this script is limited to "?tid=..." instead I do also want to track the UTM code on button click also
i.e. Grab from current page the paramater of URL https://www.optin-page.com/?tid=facebookad1?utm_campaign=blogpost then on button click grab parameters and add to button set URL https://www.sales-page.com/?tid=facebookad1?utm_campaign=blogpost
Please now find here the Code below in use for auto-redirect and grabbing the URL parameters. This code shall be changed now to be able to create a button with a click-event to be redirect then to the forward URL with parameter grabbing of current URL if the button is clicked (as stated above).
<p><!-- Modify this according to your requirement - core script from https://gist.github.com/Joel-James/62d98e8cb3a1b6b05102 and suffix grabbing </p>
<h3 style="text-align: center;"><span style="color: #ffffff; background-color: #039e00;">►Auto-redirecting after <span id="countdown">35</span> seconds◄</span></h3>
<p><!-- JavaScript part --><br /><script type="text/javascript">
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
// Total seconds to wait
var seconds = 45;
function countdown() {
seconds = seconds - 1;
if (seconds < 0) {
// Chnage your redirection link here
var tid = findGetParameter('tid');
window.location = "https://www.2share.info/ql-cb2/" + '?tid='+tid;
} else {
// Update remaining seconds
document.getElementById("countdown").innerHTML = seconds;
// Count down using javascript
window.setTimeout("countdown()", 1000);
}
}
// Run countdown function
countdown();
</script></p>
var updateQueryStringParameter = function (key, value) {
var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
urlQueryString = document.location.search,
newParam = key + '=' + value,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (urlQueryString) {
var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');
if( typeof value == 'undefined' || value == null || value == '' ) {
params = urlQueryString.replace(removeRegex, "$1");
params = params.replace( /[&;]$/, "" );
} else if (urlQueryString.match(updateRegex) !== null) {
params = urlQueryString.replace(updateRegex, "$1" + newParam);
} else {
params = urlQueryString + '&' + newParam;
}
}
// no parameter was set so we don't need the question mark
params = params == '?' ? '' : params;
window.history.replaceState({}, "", baseUrl + params);
};
I think something like this would work, upgrading the #Marc code:
//view-all parameter does NOT exist
$params = $_GET;
if(!isset($_GET['view-all'])){
//Adding view-all parameter
$params['view-all'] = 'Yes';
}
else{
//view-all parameter does exist!
$params['view-all'] = ($params['view-all'] == 'Yes' ? 'No' : 'Yes');
}
$new_url = $_SERVER['PHP_SELF'].'?'.http_build_query($params);