Cookies returning undefined - javascript

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

Related

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 and passing Cookies issue

I am working on a script which takes the vertical scroll posistioning of a div container and on document unload it stores the vertical posistion within a cookie and then loads it on load.
Originally I had the following:
$('#GridViewContainer').load('claims.php', function() {
$(this).scrollTop($(this).prop("scrollHeight") - $(this).height());
});
Which is ok if you are refreshing the page but if you are reloading the page with parameters it will lose it's position. Solution? Store it in a cookie...
However I am having issues with storing the value and loading it on load. I am using php to return all current Cookies and I can see I am setting the cookie "div_yCookie" but the content seems to be:
'div_yCookie' => string '[object Object]' (length=15)
(I am a complete Javascript and jQuery novice... No doubt it is something obvious but can someone help?
<script>
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);
}
$(document).ready(function () {
$('#GridViewContainer').load('claims.php', function() {
var x = readCookie('div_yCookie');
$(this).scrollTop($(this).prop("scrollHeight") - x);
//$(this).scrollTop($(this).prop("scrollHeight") - $(this).height());
});
});
window.onbeforeunload = function(){
var div_y = $('#GridViewContainer').scrollTop($('#GridViewContainer').prop("scrollHeight") - $('#GridViewContainer').height());
createCookie('div_yCookie',div_y,0.5);
};
</script>
UPDATE
It turns out it actually works when you refresh the page however it still doesn't work when you reload the page.

HTML - Store checkbox value locally and retrieve

I am developing a HTML web application. I have five checkboxes and I have to store the checked values locally when I click SAVE sutton. I have to retrieve the checked data from the local storage and display it when I click SHOW button. I have no idea how to do this. Help me to complete this. Thanks in advance.
Try this:
http://jsfiddle.net/sQuEy/4/
Remember that to set a checkbox value in javascript you need to use a boolean value, but web storage saves all values as strings. So:
checkboxes[i].checked = localStorage.getItem(checkboxes[i].value) === 'true' ? true:false;
Try out this code
Incorporating three simple functions from quirksmode, you can do this:
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);
}
createCookie("checkboxes", $("input:checkbox").serialize(), 30);
alert(readCookie("checkboxes"));

get and set cookie values in array position

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.

How to find out user clicked 3 times through my website with Javascript

Is there any way in JavaScript how to find out user clicked through the same domain 2 or more times?
I need to popup a window after user clicked anywhere on the site for 3 times. I know how to do it after one click - with document.referrer or addEventListener, but then I'm lost.
I need something that will capture all click events (not only links) and count them.
Sure. You need to store a list of users' click events, either in a cookie, or in a server-side data store. On every recorded click, increment the count by one, and do your thing when the number hits 3.
Try using session cookies to store state between pages -- they're fast, pretty widely compatible, and will zero out when the browser shuts down, to keep from spamming your users' cookie jars.
I tried this and it worked fine:
window.onload = function() {
var clicked = readCookie('popunder');
if(clicked == null) {
clicked = 0;
}
var allLinks = document.getElementsByTagName("a");
for(i=0;i<=allLinks.length;i++) {
allLinks[i].addEventListener("click",countClicks,true);
}
function countClicks() {
if(clicked == 2) {
popunder(); //something to do
} else {
clicked++;
doCookie('popunder', clicked, 1);
alert(clicked);
}
}
function popunder() { alert('thats 3 clicks!'); }
function doCookie(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 readName = name + "=";
var cSplit = document.cookie.split(';');
for(var i=0;i < cSplit.length;i++) {
var sc = cSplit[i];
while (sc.charAt(0)==' ') sc = sc.substring(1,sc.length);
if (sc.indexOf(readName) == 0) return sc.substring(readName.length,sc.length);
}
return null;
}
}
Thanks for all your advice.
I tried this code. But after the refresh the clicked variable goes to 0 again.
I need to save every new value of clicked into cookie (or whatever else), so its number will rise with every click on link on page.
Is it possible to change value of the variable in cookie this way?
window.onload = function(){
var **allLinks** = document.getElementsByTagName("a");
var **clicked** = 0;
**doCookie**('popunder',clicked,1);
for(i=0;i<=allLinks.length;i++){
allLinks[i].addEventListener("click",countClicks,true);
}
function **countClicks**(){
if(clicked == 3){
popunder(); //something to do
}
else{
alert(readCookie('popunder'));
return clicked++;
}
}
function **doCookie**(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 readName = name + "=";
var cSplit = document.cookie.split(';');
for(var i=0;i < cSplit.length;i++) {
var sc = cSplit[i];
while (sc.charAt(0)==' ') sc = sc.substring(1,sc.length);
if (sc.indexOf(readName) == 0) return sc.substring(readName.length,sc.length);
}
return null;
}

Categories