I have this script in JS
function setCookie(name, value, days) {
var d = new Date;
d.setTime(d.getTime() + 24*60*60*1000*days);
document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}
I can see in my Chrome browser options->settings that the cookie name "workLocation" is set. The domain for the cookie is "/", 'send for' option is "Any kind of Connection" and 'accessible to script' option is "Yes".
when I call the cookie using JS code below, it returns null.
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
alert(getCookie("workLocation"));
I had tried using PHP to show cookies var_dump($_COOKIE); but it only shows codeigniter cookies "ci_session" and "httpUser". I had used the same javascript to set and get cookies and it's working, except for this page. Any ideas how to solve it?
cookie in server and in client is different the cookie in server is stored in
Local Storage
and the cookie in client is stored in
Cookies
if you want to get the cookie from js u can use this functions :
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() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
but if you want to get the cookie from php especially those session in CI
u can use this command $this->session->userdata("key");
Related
I'm currently building a music blog which uses the following JavaScript code to toggle dark mode / light mode buttons:
function swapStylesheet(sheet) {
document.getElementById('swap').setAttribute('href', sheet);
}
My issue is that the website reverts back to the default CSS sheet whenever the page is refreshed or a new page is visited, instead of remembering the chosen theme. Might I be able to have my website remember the user's last chosen theme via cookies or localstorage or something else?
Please let me know! Thank you so much. =]
Short answer is yes.
You could save it via Cookies or Local Storage, and there's many ways to achieve this, I'll just give you reference for cookies, you could test it on W3School
The question you gave right now is only for between pages, but in cases that you want it to retain based on user accounts, then the answer is you need to centralize the "Theme" data for each account somewhere like Database or Server Cache.
https://www.w3schools.com/js/js_cookies.asp
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let 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() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
checkCookie();
I recently had issues using javascript cookies inside an MTurk HIT. In particular I'm trying to track user preferences w.r.t showing/hiding the HIT instruction.
My approach so far is the following:
<body>
<div id='instructionButton'>
<!-- Button triggering instruction body to collapse/show -->
</div>
<div id='instructionBody'>
<!-- Instruction content (collapsible) -->
...
</div>
</body>
<script>
const instructionBodyId = 'instructionBody';
const instructionButtonId = 'instructionButton';
const cookieName = 'my_cookie_name';
var isInstructionShown = true;
var instrContent = $('#' + instructionBodyId);
var instrButton = $('#' + instructionButtonId);
function setCookie(name, value) {
var date = new Date();
<!-- Cookie valid for 48h -->
date.setTime(date.getTime() + (48 * 60 * 60 * 1000));
var expires = "; expires=" + date.toUTCString();
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(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 toggleInstructions(isShow) {
setCookie(cookieName, isShow);
isInstructionShown = isShow;
if (isShow) {
instrContent.slideDown();
} else {
instrContent.slideUp();
}
}
function prepare_cookie() {
instrButton.click(function() {
toggleInstructions(!isInstructionShown);
});
let cookieVal = getCookie(cookieName);
if (cookieVal == "false") {
toggleInstructions(false);
} else {
toggleInstructions(true);
}
}
$(document).ready(function() {
prepare_cookie();
});
</script>
The code above shows part of the HIT layout I'm creating, and when testing it out while editing the HIT directly in MTurk, the cookie works as expected (it shows up in Google Chrome and works as expected, showing/hiding the instruction automatically).
Unfortunately, when publishing the HIT, the cookie does not seem to be set (it does not appear in the list of cookies shown in Google Chrome).
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 wanna use my javascript cookie to let the application see if the user already loggedIn.. i get the value of the cookie in my console.. but whenever i make an statement and wanna hide a div the div doesn't do anything it doesn't show or hide.. can you guys please help me??
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(name.length,c.length);
}
}
return '';
}
var user = readCookie('email');
if (!user) {
document.getElementById('loginNav').style.display = 'block';
document.getElementById('username').style.display = 'block';
$("#loginNav").css("display","block");
}else{
$("#loginNav").css("display","block");
console.log( $("#loginNav").css("display","block"));
}
if $('#loginNav').length == 0 then your element has not been loaded yet.
Ensure that this code comes after your jquery link and it is surrounded by a :
$(document).ready(function(){
var user = readCookie('email');
if (!user) {
$('#loginNav, #username').show();
}else{
$("#loginNav, #username").hide();
//did you forget to hide the username?
}
});
Make sure you load all your JS files at the end of your HTML age.
Hi set the "display" property to "none" to hide.... and "block" to show
I would also use "visibility":
if (!user) {
$("#loginNav, #username").css("display","block");
$("#username, #username").css("visibility","visible");
}else{
$("#loginNav, #username").css("display","none");
$("#username, #username").css("visibility","hidden");
}
I am trying to use a cookie to store a single integer, so when the user refreshes the page I am able to retrieve the previous number they were on (in an attempt to stop doubles of a video appearing).
What would the minimum requirements be to accomplish this?
var randomNumber = Math.floor((Math.random()*10)+1);
document.cookie=(randomNumber);
Setting a cookie:
document.cookie = 'mycookie=' + randomNumber + ";max-age=" + (300) + ";";
Reading a cookie:
var cookie = document.cookie;
alert(decodeURIComponent(cookie));
The cookie contains some other random stuff like push=1 as well as mycookie. Should I be setting the cookie to null before I add the randomNumber?
As far as getting the value of mycookie would I just assign the cookie to a string and parse mycookie from it?
Tamil's comment is solid. Use these quirksmode functions if you ever wish to surpass minimal cookie usage:
cookie_create = function (name,value,days) {
var expires, date;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
expires = date = null;
};
cookie_read = function (name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
len = ca.length,
i, c;
for(i = 0; i < len; ++i) {
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);
}
nameEQ = name = ca = i = c = len = null;
return null;
};
cookie_erase = function (name){
cookie_create(name,"",-1);
name = null;
};
You could use document.cookie to read/write cookies in javascript:
document.cookie = 'mycookie=' + randomNumber + '; path=/';
And if you wanted the cookie to be persistent even after the user closing his browser you could specify an expires date.