get and set cookie values in array position - javascript

OK, I have the logic, but unsure how to write to specific positions in a cookie that are separated with a pipe, |
For example - take a cookie with 0|0|0|0
if global variable is set to Y, then write the values c and d to the 2nd & 3rd position(assuming array) if the cookie exists - if the cookie doesn't exist then create a cookie with 0|0|c|d
if the global variable is null then write the values a and b to the 0 and 1st position if the cookies exists - if the cookie doesn't exist then create a cookie with a|b|0|0
I understand getting a cookie, and splitting the cookie to get a value, but unsure how to write to specific positions. I'm assuming using "join".
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);
}

Assuming your desired cookie value was named "pipes" and your variable was named globalVar, you could do something like this:
var val = readCookie("pipes") || "";
var valArray = val.split("|");
if (valArray.length >= 4) {
if (globalVar == "Y") {
valArray[2] = 'c';
valArray[3] = 'd';
} else if (globalVar == null) {
valArray[0] = 'a';
valArray[1] = 'b';
}
val = valArray.join("|");
} else {
// fully formed cookie value didn't exist
if (globalVar == "Y") {
val = "0|0|c|d";
} else {
val = "a|b|0|0";
}
}
createCookie("pipes", val, 365);
I must say that storing this piped value in the cookie is very inconvenient and requires more code than is probably required to just store and retrieve multiple values from a cookie.
From your comments, it sounds like the data is storeID|storeLocation and you have two of those. I'd suggest you just do this:
var store1 = readCookie("store1"); // "1640|Jacob's Point"
var store2 = readCookie("store2"); // "2001|Fred's Point"
Or, if you want to make a function, you can do this:
function readStoreInfo(item) {
var info = readCookie(item);
if (info) {
var data = info.split("|");
return({id: data[0], name: data[1]});
}
return(null);
}
function writeStoreInfo(item, obj) {
var val = obj.id + "|" + obj.name;
createCookie(item, val, 365);
}
So, to read the data for store1, you would just call:
var store1Info = readStoreInfo("store1");
store1Info.id = 123;
writeStoreInfo("store1", store1Info);
You can then read and write the data for store1 and store2 independently.

Related

How to create page visit counting like PHP session on JavaScript (client) side

Is it possible to create a session number of page view/visit like PHP, but in JavaScript?
$_SESSION['views'] = 0;
Is it possible to keep track of the number even when user quite the page and get back again?
You could use Cookies. On visit get the cookie and increment it by 1. Or set it to 1 if it doesn't exist
Example:
<p id="yolo"> </p>
<script>
var numberOfVisits = function getCookie('numberOfVisits');
if (numberOfVisits == "")
{
setcookie('numberOfVisits', 1, 100);
}
else
{
numberOfVisits++;
setcookie('numberOfVisits', numberOfVisits, 100);
}
document.getElementById('yolo').innerHTML = getCookie('numberOfVisits');
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
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
{
var expires = "";
}
document.cookie = name+"=" + value+expires + ";path=/";added
}
</script>
If you only need the data on the client side then use
window.localStorage, it stores data with no expiration date on the client side and it does not send it to the server on every request like cookies, as explained here.
<script>
var varname = "VISIT_COUNTER";
if (localStorage.getItem(varname) === null) {
localStorage.setItem(varname, 1);
} else {
var visits_count = parseInt(localStorage.getItem(varname)) + 1;
localStorage.setItem(varname, visits_count);
console.log("Total visits: " + visits_count);
}
</script>

Logical Operator always stays true?

What I want is to compare current url with my cookie array which would contain all the URL's a user has visited so it would compare that whether the array contains the current link or not so if not it would push that new link to the array and would again recreate the cookie with the new array which would contain the new pushed link so what I am facing right now is that everytime the if function which checks for the unique link always comes true I am not sure that what's the problem?
Can you people please have a look over it :
<script type="text/javascript">
function createCookie(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=/";
}
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);
}
var url = window.location.href;
var pathname = new URL(url).pathname;
var jsonObj = [];
//jsonObj.push("test");
var x = readCookie('vid_cookies');
if (x) {
var res = x.split(",");
console.log(res);
for (var i = 0; i < res.length; i++) {
if (pathname != res[i]) {
alert("IS NOT EQUAL");
//res.push(pathname);
//var joinedArray = res.join(",");
//console.log(joinedArray);
//createCookie('vid_cookies',joinedArray,7);
//var z = readCookie('vid_cookies');
//console.log(z)
}
}
} else {
jsonObj.push(pathname);
createCookie('vid_cookies',jsonObj,7);
}
//alert(jsonObj);
</script>
Here is the Array as :
["/evercookie-master/yahoo.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html"]
The logic is not correct. If you want to add a value to an array only if it doesn't exist yet, you have to check all elements before you add it.
In your code you are adding the value as soon as any of the element doesn't match. That will always be the case of course because out n elements, n - 1 will not match.
One way to do it would be to use Array#every:
if (res.every(x => x !== pathname)) {
// add to array and set cookie
}
Alternatively you could convert the array to a Set, always add the value and set the cookie. The Set will automatically dedupe the values:
var res = new Set(x.split(","));
res.add(pathname);
res = Array.from(res);

Javascript check if url param exists

I'm running an A/B test to see if showing more items is better for conversion. But it seems that the code sometimes causes errors.. But I can't find any errors and don't know when they occur.
In my test I check whether the url param IC exists and if it doesn't exists I will add this.
This is my code:
function checkIfAlreadyPaginated()
{
var field = 'IC';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1)
return true;
else if(url.indexOf('&' + field + '=') != -1)
return true;
return false;
}
function insertParam(key, value) {
key = encodeURIComponent (key); value = encodeURIComponent (value);
var kvp = document.location.search.substr(1).split('&');
if (kvp == '') {
return '?' + key + '=' + value;
}
else {
var i = kvp.length; var x; while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
return '?'+kvp.join('&');
}
}
var itemsPerPage = 48;
if(!checkIfAlreadyPaginated())
{
document.location.search = insertParam('IC', itemsPerPage);
}
Does someone spot possible issues? I'm running the test via VWO.com.
If there is a Javascript error you should see it in the browser console and share it with us.
In any case, I would do it by creating a JS Object first. I find it easier to work with.
In the following code I added the option to do the checking for multiple params of the querystring. If you only need to check the IC you can simplify it a bit. I tested it on a blank test.html.
<script type="text/javascript">
// get the current params of the querystring
var querystringItems = document.location.search.substr(1).split('&');
// create an object
var querystringObject = {};
for(i=0;i<querystringItems.length;++i) {
param = querystringItems[i].split('=');
querystringObject[param[0]] = param[1];
}
// Define the keys to be searched for and their default value when they are not present
var requiredKeys = {"IC":48, "test": "me"};
// Do the checking on the querystringObject for each requiredKeys
var doreload = false;
for (var key in requiredKeys) {
if (typeof querystringObject[key] == 'undefined') {
doreload = true;
// Create the missing parameter and assign the default value
querystringObject[key] = requiredKeys[key];
}
}
// If any of the requiredKeys was missing ...
if (doreload) {
// rebuild the querystring
var querystring = '?';
for (var key in querystringObject) {
querystring+=key+'='+querystringObject[key]+'&';
}
querystring=querystring.substr(0,querystring.length-1);
// reload page
document.location.search = querystring;
}
// assign the values to javascript variables (assuming you had it like this because you needed it)
var itemsPerPage = querystringObject.IC;
</script>
Here is an example to check this:
//get URL params into string:
paramStr = window.location.substring(window.location.indexOf('?'), window.location.length;
//turn string into array
paramArray = paramStr.split('&');
//prepare final array of params
params = {};
//prepare the index of IC parameter
icLoc = -1; //this is negative 1 so that you know if it was found or not
//for each item in array
for(var i in paramArray){
//push its name and value to the final array
params.push(paramArray[i].split('='));
//if the parameter name is IC, output its location in array
if(params[i][0] === 'IC'){
icLoc = i;
}
}
If IC is not found, icLoc will be -1.
If it is found, the value of IC in the URL parameters is params[icLoc][1]
Example result for query string ?foo=bar&code=cool&IC=HelloWorld:
params = {'foo': 'bar', 'code': 'cool', 'IC': 'HelloWorld'}
icLoc = 2
Example for query string ?foo=bar&code=cool:
params = {'foo': 'bar', 'code': 'cool'}
icLoc = -1
Here id is the param I'm using for a test. Pass the argument which you want to check whether it exists or not.
function queryParamExistUrl(param = '') {
if (new URLSearchParams(window.location.search).get(param) != null)
return true
return false
}
console.log(queryParamExistUrl('id'))

Cookies returning undefined

I'm building a small HTML game that uses cookies/localStorage to save and load users data. I have an object declared that holds all of the data which is then referenced by the save/load functions and by game calculations:
var iAttack, iDefence, iGold;
// nothing to do with Apple lol...
var data = {
pStats: {
attack: iAttack,
defence: iDefence
},
pInventory: {
gold: iGold
}
}
These will obviously return undefined, but this is before the cookie values are inserted.
So, heres a run-through of whats supposed to happen:
When the window loads, the if statements are gone through to check cookies/localStorage and if there is any previous storage data in the browser. These booleans get assigned to cookies, storageLocal and previousData. This is the code for it:
var previousData = false;
var cookies = false;
var storageLocal = false;
//activated on window.load
function loadData(){
//check for previous data
if (document.cookie != "") {
previousData = true;
console.log("Previous data? " + previousData)
} else if (localStorage.getItem("gold") !== null) {
previousData = true;
console.log("Previous data? " + previousData)
} else {
console.log("Previous data? " + previousData)
}
// check if cookies/localStorage
document.cookie = "foo=bar";
if(document.cookie){
cookies = true;
console.log("Cookies will be used")
} else if (typeof(localStorage) != undefined){
storageLocal = true;
console.log("localStorage will be used")
}
// loadData() continued...
If previousData = false then default values are assigned to the object variables, eg iDefence = 5 and this works fine.
Lets assume that previousData and cookies are true: the function then goes on to inserting the data from the cookies into the object variables like this:
if (previousData) {
if (cookies){
data.pStats.attack = parseInt( readCookie("attack") );
data.pStats.defence = parseInt( readCookie("defence") );
// note that i've used iAttack instead of data.pStats.attack but doesn't work
In the console, if i input iAttack or data.pStats.attack it returns undefined. This is the problem that been keeping me up all of last night trying to work around. Any help would be really appreciated.
This is the saveData function that is triggered by onclick. It inputs the object values into cookies:
function saveData(){
if(cookies){
createCookie("attack", iAttack, 7);
createCookie("defence", iDefence, 7);
//if its the first time saving then the default values of iAttack/def will be used
If you're curious about createCookie() and readCookie(), these are the functions:
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);
}

Javascript - How to display only the value of a cookie?

I have searched several places trying to find out how to do display only the value of a cookie rather than the whole key but they all seemed needlessly complex for what I'm doing. I've got a single cookie with only one key, userName = something, and I can't figure out how to display only the "something" rather than userName = something.
function userCookie(form)
{
if(form.User_Name.value == "")
{
alert("Cannot accept a blank user name, please enter a valid name");
return false;
}
else
{
document.cookie="userName=" + form.User_Name.value;
alert(document.cookie);
return false;
}
}
function newWindow()
{
var userWindow = window.open("","MyUserName","height=300,width=300");
userWindow.document.open();
userWindow.document.write("<p>Welcome Back</p>");
userWindow.document.write(document.cookie);
userWindow.document.close();
}
If you always have exactly one cookie then document.cookie.split("=")[1] would be simple enough.
document.cookie will always return key,value pair like cookie1=value1;cookie2=value2.
You can use the following function to split the cookieName and "=" from the document.cookie to get the value.
function getCookie(cname) {
var name = cname + "=";
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);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
The code is from w3schools.
var cookieArray = document.cookie.split("; "),
cookieObject = {},
i, pair;
for (i = cookieArray.length - 1; i >= 0; i--) {
pair = cookieArray[i].split("=");
cookieObject[pair[0]] = pair[1];
}
alert(cookieObject.userName);
function getCookie(name) {
let x = document.cookie.split(";").find(a => a.includes(name + "="));
return !!x ? x.trim().substr(name.length+1) : ""
}

Categories