I have two firebase scripts; one of them is working fine but other not. I don't have any idea what is going on. Those two scripts are based on same logic. Only difference is that counter 2 data is always incremented irrespective of website home page or post page while counter 1 data is incremented only it is post page (i.e. pathname!='/'). Fortunately counter 1 is working fine but counter 2 not. I don't have any idea what i'm doing wrong..
Please help me to get rid of this bug. Any kind of help would be appreciated.
$(function(){
var parentDataRef = 'https://blablabla.firebaseio.com/';
//counter 1
var postRef = new Firebase(parentDataRef+'one');
getFirebaseData(postRef,'post',function(pData){
alert(pData);
});
//counter 2
var blogRef = new Firebase(parentDataRef+'two');
getFirebaseData(blogRef,'blog',function(bData){
alert(bData);
});
});
//get Firebase data
function getFirebaseData(r,bp,back){ //Reference, Blog or Post, Return data
var doctitle = document.title;
r.once('value', function(e) {
var data=e.val();
if (data==null){data=1;}
else if (getCookie(doctitle)!='yes'){
if (bp=='post' && window.location.pathname!='/') {data++;}
else if (bp=='blog') {data++;}
}
r.set(data);
back(data);
setCookie(doctitle,'yes',7);
});
}
//set Cookie Data
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+'='+cvalue+'; '+expires+'; path=/';
}
//get Cookie Data
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) == 0) {
return c.substring(name.length, c.length);
}
}
return '';
}
Can I suggest to use transactions your counters ?
var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
return (current_value || 0) + 1;
});
Related
I saw the age-verification snippet solution for my problem and it worked great. But in that solution the occurrence of that popup is based on the number of days. I want the popup to occur every time the user enters my website. How to do it?
Here's is the JS part of the snippet code.
<script>
function ageCheck() {
var min_age = {{ age }}; // Set the minimum age.
var year = parseInt(document.getElementById('byear').value);
var month = parseInt(document.getElementById('bmonth').value);
var day = parseInt(document.getElementById('bday').value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ((today.getTime() - theirDate.getTime()) < 0) {
window.location = 'http://google.com'; //enter domain url where you would like the underaged visitor to be sent to.
} else {
var days = 1; //number of days until they must go through the age checker again.
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = 'isAnAdult=true;'+expires+"; path=/";
location.reload();
};
};
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;
};
var isAnAdult = readCookie('isAnAdult');
if (isAnAdult) {
document.write("<style> #prompt-background { display: none; }</style>");
};
</script>
and the button that function is called on
<button id="submit_birthdate" class="exitbutton" onclick="ageCheck()">Enter</button>
How to modify this code so that the popup appears every time?
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I'm working on a project that I set functions to create a cookie based off of a form value. That cookie then populates another form's input values. At first, I only needed to set three cookies, so this wasn't overly big (calling the functions)... the requirements changed, and I went from needing three cookies to now needing eight, so my function calls are getting a little out of hand. Is there a more efficient way of doing this?
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
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) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie(c, el) {
var user = getCookie(c);
if (user != "") {
document.getElementById(el).value = user;
document.getElementById(el).setAttribute("value", user);
document.getElementById(el).setAttribute("readonly", "readonly");
}
}
function setEmployee(e, field) {
var emp = getCookie(e);
if (emp != "") {
document.getElementsByClassName(field).value = emp;
var perm = document.getElementsByClassName(field);
perm[0].setAttribute("value", emp);
}
}
$(document).ready(function(){
var firstName = "firstName";
var lastName = "lastName";
var phoneCookie = "phone";
var emailCookie = "email";
var companyCookie = "company";
var addressCookie = "address";
var stateCookie = "state";
var zipCookie = "zip";
$('#form').submit(function(){
var first = $('#FirstName').val();
var last = $('#LastName').val();
var phone = $('#Phone').val();
var email = $('#Email').val();
var company = $('#Company').val();
var address = $('#Address').val();
var state = $('#State').val();
var zip = $('#PostalCode').val();
setCookie(firstName, first, 10);
setCookie(lastName, last, 10);
setCookie(phoneCookie, phone, 10);
setCookie(emailCookie, email, 10);
setCookie(companyCookie, company, 10);
setCookie(addressCookie, address, 10);
setCookie(stateCookie, state, 10);
setCookie(zipCookie, zip, 10);
});
if($('#census').is(':visible')){
checkCookie(firstName, "contactName");
checkCookie(lastName, "contactLast");
checkCookie(phoneCookie, "contactPhone");
checkCookie(emailCookie, "contactEmail");
checkCookie(companyCookie, "contactCompany");
checkCookie(addressCookie, "contactAddress");
checkCookie(stateCookie, "contactState");
checkCookie(zipCookie, "contactZip");
}
});
Using both internet and Stack Overflow resources I managed to write a crude HTML website, that allows the user to switch Language of it on the fly, using Javascript, jQuery and XML.
Now, the problem I ran into is to keep the preferred language across the entire portal, without the need to change it each time when navigating through it. I have decided to use a simple cookie to keep the track of it, but it seems I have messed something up, and I can't figure out what I'm doing wrong.
Basically speaking, the page itself has text in the code itself (as a backup just in case), however the text becomes invisible when booting the site, until I switch a language, nor the language is kept when I navigate the portal. For the former, I assumed that the script was reading some empty or overall wrong cookie, so I made an attempt to filter it out and use a default language, but in vain. As for the latter issue, I guess I save the cookie itself wrong as well, but I can't seem to figure out what's wrong with it.
Any help/advice would be appreciated.
function changeLanguage(lang) {
$(function() {
$.ajax({
url: 'jezyki.xml',
success: function(xml) {
$(xml).find('translation').each(function(){
var id = $(this).attr('id');
var text = $(this).find(lang).text();
$("." + id).html(text);
if (lang === "") { }
else {
var title = lang;
createCookie("language", title, 365);
}
});
}
});
});
}
$(document).ready(function () {
$("input[name='radio-language']").click(function () {
changeLanguage($(this).val());
});
});
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 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;
}
window.onload = function (e) {
var cookie = readCookie("language");
var domyslny = "english";
if (title === "") { changeLanguage(domyslny); } else { changeLanguage(title); }
}
Apologies if this is something silly, I am quite a newbie when it comes to Javascript/jQuery.
I'm trying to figure out how to track how many pages a user vists via cookies. I just want to count how many pages they visit, and on the 3rd page, display a newsletter signup form. This is my current script, which doesn't have any counting mechanism:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
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) == 0) return c.substring(name.length,c.length);
}
return "";
}
var hidePopoverCookie = getCookie("hidePopover");
if (hidePopoverCookie == "") { // && pagesVisited > 2
setTimeout(function() {
$("#popOver").show();
}, 5000);
}
$("#popOver button").click(function() {
$("#popOver").hide();
setCookie("hidePopover", true, 365);
})
And this is what I'm trying to implement as a page counter:
var pagesVisitedCookie = getCookie("pagesVisited");
if (pagesVisitedCookie === "") {
console.log ("no pages visited");
setCookie("pagesVisted", 1, 365);
} else if (pagesVisitedCookie === 1) {
console.log("2 pages visited");
setCookie("pagesVisted", 2, 365);
} else if (pagesVisitedCookie > 2) {
console.log("More than 2 pages visited");
setCookie("pagesVisted", 3, 365);
}
What happens is it returns "no pages visited" no matter what, and I'm not sure why. I'm very new to cookies, and I'm sure there's a cleaner way to do this, I just want to get it done (this project is making me insane).
Since I see you are already using jQuery, I will use it to as the wrapper function of which will trigger than actual logic on DOM loaded event, then you I could use sessionStorage like so:
$(function(){ // fires once a page's DOM is ready
var visitsCount = JSON.parse(sessionStorage.getItem('visitsCount'));
if( visitsCount.legnth < 3 && $.inArray( window.location.href, visitsCount ) == -1 ){
visitsCount.push(window.location.href);
sessionStorage.setItem('visitsCount', JSON.stringify(visitsCount));
}
if( visitsCount.legnth >= 3 ) // user has viewed 3 different pages
// do whatever
});
The code is storing the current URL of the page in the sessionStorage, if that URL isn't in the stored array already.
You are setting a cookie named pagesVisted, while you are reading a cookie named pagesVisited.
I am using the scripts from here http://www.quirksmode.org/js/cookies.html and have successfully created a cookie.. it is set based on the users response to the age drop down. However I am having trouble doing anything with it. I would like to have a style defined if a cookie is present. Here is the bulk of my scripts..
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 checkAge(){
var min_age = 13;
var year = parseInt(document.forms["emailForm"]["year"].value);
var month = parseInt(document.forms["emailForm"]["month"].value) - 1;
var day = parseInt(document.forms["emailForm"]["day"].value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ( (today.getTime() - theirDate.getTime()) < 0) {
var el = document.getElementById('emailBox');
if(el){
el.className += el.className ? ' youngOne' : 'youngOne';
}
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
createCookie('age','not13',0)
return false;
}
else {
createCookie('age','over13',0)
return true;
};
};
window.onload=function(){
var x = readCookie('not13');
if (x) {
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
}
}
Age verification works and cookie is set.... no errors (from Firebug).. can anyone see what I am doing wrong?
with jQuery would be something like this
if (x) {
var style = "<style type=\"text/css\">.form {display:none}</style>";
$("header").append(style);
}
Looking at your code it should work. There's nothing incorrect about it.
The only thing I would suggest is that instead of injecting a style tag into a empty div, inject a link tag into the head. This will mean that your css changes and maintainance won't need to touch the js code.
I got it.. I was looking for the cookie value and needed to look for the name and then create an if statement based on the value. so..
var x = readCookie('age');
if (x=='not13') {
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
}