I am trying to hide an element on the front-end and remember the user choice by creating a cookie in PHP.
Here is how I have it set up:
I have some HTML and JS scripts inside an HTML widget on the page on the front-end
<div id="training-banner"> training banner design here </div>
<button onclick="myFunction()" id="close-btn">X</button>
<script>
function myFunction() {
var element = document.getElementById("training-alert");
element.classList.add("hidebanner");
}
</script>
Then I have written the cookie function inside the function.php of the child theme:
add_action('init', function() {
if (!isset($_COOKIE['training_banner_cookie'])) {
setcookie('training_banner_cookie', 'showbanner', strtotime('+1 day'));
}
if (class_exists('hidebanner')){
?><style>#training-alert{display:none;}</style> <?php
setcookie('training_banner_cookie', 'hidebanner', strtotime('+1 day'));
}
$cookieValue = $_COOKIE['training_banner_cookie'];
if ($cookieValue == "hidebanner"){
?><style>#training-alert{display:none;}</style> <?php
}
});
For some reason, the class_exists() PHP function does not work, any idea how this can be achieved?
https://www.php.net/manual/en/function.class-exists.php
class-exists is not used in your case. It is used to check if a Class exists in your PHP code block.
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
What you want to do is to save the choice of the users' choice. You can simply use JS to achieve it.
<div id="training-banner"> training banner design here </div>
<button onclick="myFunction()" id="close-btn">X</button>
<script>
function getCookie(cookieName: string, cookie?: string): string {
const name = cookieName + '='
const decodedCookie = decodeURIComponent(cookie || document.cookie)
const 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 setCookie(
cookieName,
value,
days,
isSecure = true
): void {
let expires = ''
const secure = isSecure ? '; Secure' : ''
if (days) {
const date = new Date()
date.setTime(date.getTime() + days * 86400000)
expires = ' ;expires=' + date.toUTCString()
}
document.cookie = cookieName + '=' + value + expires + ' ;path=/' + secure
}
function myFunction() {
var element = document.getElementById("training-alert");
element.classList.add("hidebanner");
setCookie('training_banner_cookie_hide', true, 1)
}
function init(){
var shouldHideBanner = getCookie('training_banner_cookie_hide')
if(shouldHideBanner){
var element = document.getElementById("training-alert");
element.style.display = 'none';
}
}
init()
</script>
With the help of #WillyLi's answer, I was able to organize my thoughts and modify his code a bit here is what worked for me:
I modified the getCookie function declaration and simplified it to one parameter cname.
Then I also modified the setCookie and standardized it according to w3school
Finally, I wanted the banner to be hidden immediately as the user clicks the button so I added element.style.display = 'none'; to myFunction()
Here is what the final version looks like:
<button onclick="myFunction()" id="close-btn">X</button>
<script>
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 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 myFunction() {
var element = document.getElementById("training-alert");
element.style.display = 'none';
setCookie('training_banner_cookie_hide', true, 1);
}
function init(){
var shouldHideBanner = getCookie('training_banner_cookie_hide');
if(shouldHideBanner){
var element = document.getElementById("training-alert");
element.style.display = 'none';
}
}
init()
</script>
I'm learning JavaScript and I see that this question has been asked many times, but I can't get this to work for me.
What I want to do is, show a bootstrap modal once a day.
What I have so far is:
function setCookie(cookiename, cookievalue, expdays) {
var d = new Date();
d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cookiename + "=" + cookievalue + "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal,
//if there is a cookie then return;
//The cookie should expire in one day.
function checkCookie() {
var showed = getCookie("showed");
if (showed != null && showed != "") {
var date = new Date(showed).getDate();
var currentDate = new Date().getDate();
if (currentDate > date) {
return true;
}
return false;
}
return true;
}
Now, if I change the last return true; to return false; my modal does not show up.
The way it is now I see the modal every time.
What am I doing wrong?
How can I fix this?
function setCookie(cookiename, cookievalue, expdays) {
var d = new Date();
d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cookiename + "=" + cookievalue + "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename + "=";
var startPos = document.cookie.indexOf(name);
if(startPos == -1) return null;
startPos+=(name.length);
if(document.cookie.indexOf(";",startPos) == -1){
return document.cookie.substring(startPos,document.cookie.length);
}
else{
return document.cookie.substring(startPos,document.cookie.indexOf(';',startPos));
}
return null;
}
//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal,
//if there is a cookie then return;
//The cookie should expire in one day.
function checkCookie() {
var showed = getCookie("showed");
if (showed != null && showed != "") {
var date = new Date(showed).getDate();
var currentDate = new Date().getDate();
if (currentDate > date) {
return true;
}
return false;
}
return true;
}
Also when setting cookie,
use
setCookie('showed',new Date().toGMTString(),1);
because we are using the value of cookie, not the expire time of cookie to check. So the value must be a datestring
hi i am designing a real estate website and i have many ads in it i add an option to every of my ads and if user click on "add to favorites" that ad's id and url saves in a cookie and retrieve in "favorite page" thus user can review that certain ad every time he or she wants. each of my ads have a address like this localhost/viewmore.php?ID=a number
totally saving process in cookie works fine but recently i realized something. consider i visit one of my ads with this address localhost/viewmore.php?ID=10 and click on "add to favorite" then if i open another page with this address localhost/viewmore.php?ID=8 and then i read my cookie in "favorite page" i will see this result
[{"favoriteid":"10","url":"http://localhost/viewcookie.php?ID=10"},{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
which is perfectly true and it is what i expect.
the problem
now consider unlike the previous case i open both of ads and then click on "add to favorite" on first ad and then go to second ad (without any refreshing) and click on "add to favorite" on second ad this time if i read my cookie in "favorite page" i will see this result
[{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
which is not true i want two see both of ad's id and url in my cookie not just last one.
ps: i use push() method to add new object to cookie array i think i have to update it every time after click? any idea thanks
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
var faves = new Array();
function isAlready(){
var is = false;
$.each(faves,function(index,value){
if(this.url == window.location.href){
console.log(index);
faves.splice(index,1);
is = true;
}
});
return is;
}
$(function(){
var url = window.location.href; // current page url
var favID;
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
var favID = (pair[0]=='ID' ? pair[1] :1)
//alert(favID);
}
// this is the part i think i have to update every time without refreshing*******************************
$(document.body).on('click','#addTofav',function(e){
e.preventDefault();
if(isAlready()){
} else {
var fav = {'favoriteid':favID,'url':url};
faves.push(fav);
}
//*******************************************************************************************************
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
});
var myfaves = JSON.parse(readCookie('favespages'));
if(myfaves){
faves = myfaves;
} else {
faves = new Array();
}
});
Your problem is that you are looking at variable faves, which is initialized at document load, but it isn't being updated as cookie changes.
The second page looks at the variable, sees no favorites from first page, because it doesn't actually look at cookie.
Then, it just resets the cookie with it's values.
Here is the full code, with added functionality from chat:
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
var faves = {
add: function (new_obj) {
var old_array = faves.get();
old_array.push(new_obj);
faves.create(old_array);
},
remove_index: function (index) {
var old_array = faves.get();
old_array.splice(index, 1);
faves.create(old_array);
},
remove_id: function (id) {
var old_array = faves.get();
var id_index = faves.get_id_index(id);
faves.remove_index(id_index);
},
create: function (arr) {
var stringified = JSON.stringify(arr);
createCookie('favespages', stringified);
},
get: function () {
return JSON.parse(readCookie('favespages')) || [];
},
get_id_index: function (id) {
var old_array = faves.get();
var id_index = -1;
$.each(old_array, function (index, val) {
if (val.id == id) {
id_index = index;
}
});
return id_index;
},
update_list: function () {
$("#appendfavs").empty();
$.each(faves.get(), function (index, value) {
var element = '<li class="' + index + '"><h4>' + value.id + '</h4> Open page ' +
'Remove me';
$('#appendfavs').append(element);
});
}
}
$(function () {
var url = window.location.href;
$(document.body).on('click', '#addTofav', function (e) {
var pageId = window.location.search.match(/ID=(\d+)/)[1];
if (faves.get_id_index(pageId) !== -1) {
faves.remove_id(pageId);
}
else {
faves.add({
id: pageId,
url: url
});
}
faves.update_list();
});
$(document.body).on('click', '.remove', function () {
var url = $(this).data('id');
faves.remove_id(url);
faves.update_list();
});
$(window).on('focus', function () {
faves.update_list();
});
faves.update_list();
});
Is it possible to create a cookie using arrays?
I would like to store a[0]='peter', a['1']='esther', a['2']='john' in a cookie in JavaScript.
As you can read in this topic:
You combine the use jQuery.cookie plugin and JSON and solve your problem.
When you want to store an array, you create an array in JS and use JSON.stringify to transform it into an string and stored with $.cookie('name', 'array_string')
var myAry = [1, 2, 3];
$.cookie('name', JSON.stringify(myAry));
When you want to retrive the array inside the cookie, you use $.cookie('name') to retrive the cookie value and use JSON.parse to retrive the array from the string.
var storedAry = JSON.parse($.cookie('name'));
//storedAry -> [1, 2, 3]
Cookies can hold only strings. If you want to simulate an array you need to serialize it and deserialize it.
You could do this with a JSON library.
I add the code below Script (see the following code) into a javascript file called CookieMonster.js.
It's a wrapper around the current snippet from http://www.quirksmode.org/js/cookies.html
It works with arrays and strings, it will automagically escape your array/string's commas , and semi-colons ; (which are not handled in the original snippets).
I have listed the simple usage and some bonus usage I built into it.
Usage:
//set cookie with array, expires in 30 days
var newarray = ['s1', 's2', 's3', 's4', 's5', 's6', 's7'];
cookiemonster.set('series', newarray, 30);
var seriesarray = cookiemonster.get('series'); //returns array with the above numbers
//set cookie with string, expires in 30 days
cookiemonster.set('sample', 'sample, string;.', 30);
var messagestring = cookiemonster.get('sample'); //returns string with 'sample, string;.'
Bonuses:
//It also conveniently contains splice and append (works for string or array (single string add only)).
//append string
cookiemonster.append('sample', ' add this', 30); //sample cookie now reads 'sample, string;. add this'
//append array
cookiemonster.append('series', 's8', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8']
//splice
cookiemonster.splice('series', 1, 2, 30); //returns array with values ['s1', 's4', 's5', 's6', 's7', 's8']
CookieMonster.js :
var cookiemonster = new Object();
cookiemonster.append = function (cookieName, item, expDays) {
item = cm_clean(item);
var cookievalue = cookiemonster.get(cookieName);
if (cookievalue instanceof Array) {
cookievalue[cookievalue.length] = item;
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
} else {
cm_createCookie(cookieName, cookievalue + item, expDays);
}
};
cookiemonster.splice = function (cookieName, index, numberToRemove, expDays) {
var cookievalue = cookiemonster.get(cookieName);
if (cookievalue instanceof Array) {
cookievalue.splice(index, numberToRemove);
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
}
};
cookiemonster.get = function (cookieName) {
var cstring = cm_readCookie(cookieName);
if (cstring.indexOf('<#&type=ArrayVals>') != -1) {
var carray = cstring.split(',');
for (var i = 0; i < carray.length; i++) {
carray[i] = cm_dirty(carray[i]);
}
if (carray[0] == '<#&type=ArrayVals>') {
carray.splice(0, 1);
}
return carray;
} else {
return cm_dirty(cstring);
}
};
cookiemonster.set = function (cookieName, value, expDays) {
if (value instanceof Array) {
cm_createCookie(cookieName, cm_arrayAsString(value), expDays);
}
else { cm_createCookie(cookieName, cm_clean(value), expDays); }
};
cookiemonster.eraseCookie = function (name) {
cm_createCookie(name, "", -1);
};
function cm_replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
};
function cm_clean(ret) {
ret = cm_replaceAll(ret.toString(), ',', ',');
ret = cm_replaceAll(ret.toString(), ';', ';');
return ret;
};
function cm_dirty(ret) {
ret = cm_replaceAll(ret, ',', ',');
ret = cm_replaceAll(ret, ';', ';');
return ret;
};
function cm_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 cm_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 cm_arrayAsString(array) {
var ret = "<#&type=ArrayVals>"; //escapes, tells that string is array
for (var i = 0; i < array.length; i++) {
ret = ret + "," + cm_clean(array[i]);
}
return ret;
};
Create array in cookie using jQUery?
var list = new cookieList("test"); $(img).one('click', function(i){ while($('.selected').length < 3) {
$(this).parent()
.addClass("selected")
.append(setup.config.overlay);
//$.cookie(setup.config.COOKIE_NAME, d, setup.config.OPTS);
var index = $(this).parent().index();
// suppose this array go into cookies.. but failed
list.add( index );
var count = 'You have selected : <span>' + $('.selected').length + '</span> deals';
if( $('.total').length ){
$('.total').html(count);
}
} });
I agree with other comments - you should not be doing this and you should be using JSON. However, to answer your question you could hack this by storing the array as a comma-delimited string. Lets say you wanted to save a the following Javascript array into a cookie:
var a = ['peter','esther','john'];
You could define a cookie string, then iterate over the array:
// Create a timestamp in the future for the cookie so it is valid
var nowPreserve = new Date();
var oneYear = 365*24*60*60*1000; // one year in milliseconds
var thenPreserve = nowPreserve.getTime() + oneYear;
nowPreserve.setTime(thenPreserve);
var expireTime = nowPreserve.toUTCString();
// Define the cookie id and default string
var cookieId = 'arrayCookie';
var cookieStr = '';
// Loop over the array
for(var i=0;i<a.length;i++) {
cookieStr += a[i]+',';
}
// Remove the last comma from the final string
cookieStr = cookieStr.substr(0,cookieStr.length-1);
// Now add the cookie
document.cookie = cookieId+'='+cookieStr+';expires='+expireTime+';domain='+document.domain;
In this example, you would get the following cookie stored (if your domain is www.example.com):
arrayCookie=peter,ester,john;expires=1365094617464;domain=www.example.com
I've created this easy way to get cookies. It'll give error if execute here, but it's functional
var arrayOfCookies = [];
function parseCookieToArray()
{
var cookies = document.cookie;
var arrayCookies = cookies.split(';');
arrayCookies.map(function(originalValue){
var name = originalValue.split('=')[0];
var value = originalValue.split('=')[1];
arrayOfCookies[name] = value;
});
}
console.log(arrayOfCookies); //in my case get out: [language: 'en_US', country: 'brazil']
parseCookieToArray();
New
My new obj to create get cookies
cookie = {
set: function(name, value) {
document.cookie = name+"="+value;
},
get: function(name) {
cookies = document.cookie;
r = cookies.split(';').reduce(function(acc, item){
let c = item.split('='); //'nome=Marcelo' transform in Array[0] = 'nome', Array[1] = 'Marcelo'
c[0] = c[0].replace(' ', ''); //remove white space from key cookie
acc[c[0]] = c[1]; //acc == accumulator, he accomulates all data, on ends, return to r variable
return acc; //here do not return to r variable, here return to accumulator
},[]);
}
};
cookie.set('nome', 'Marcelo');
cookie.get('nome');
Here's the simplest form of adding a cookie in array format.
function add_to_cookie(variable, value) {
var d = new Date();
d.setTime(d.getTime() + (90 * 24 * 60 * 60 * 1000)); //equivalent to 1 month
var expires = "expires=" + d.toUTCString();
document.cookie = "cookie_name[" + variable + "]" + "=" + value + ";" + expires + ';path=/';
}
For that example you can do it quite easily:
Make Cookies:
///W3Schools Cookie Code:
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 + ";";
}
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 "";
}
///My Own Code:
for(a=0;a<b.length;a++){
setCookie(b[a],b[a],periodoftime);
}
Retrieve Array:
for(a=0;a<b.length;a++){
b[a] = getCookie(b[a])
}
For any array with other value types besides strings:
Make Cookies:
///Replace MyCode above With:
if(typeof b[a] === 'string'){
setCookie(b[a],b[a],periodoftime);
}else{
setCookie(b[a].toString,b[a],periodoftime);
}
Retrieve Array:
for(a=0;a<b.length;a++){
if(typeof b[a] === 'string'){
b[a] = getCookie(b[a])
}else{
b[a] = getCookie(b[a].toString)
}
}
The only flaw is that identical values cannot be retrieved.
No JQuery needed, comma seperation or JSON.
Added remove to cookiemonster
// remove item
cookiemonster.remove('series', 's6', 30); //returns array with values ['s1', 's2', 's3', 's4', 's5', 's7', 's8']
cookiemonster.remove = function (cookieName, item, expDays) {
var cookievalue = cookiemonster.get(cookieName);
//Find the item
for( var i = 0; i < cookievalue.length; i++) {
if ( cookievalue[i] === item) {
cookievalue.splice(i, 1);
}
}
cm_createCookie(cookieName, cm_arrayAsString(cookievalue), expDays);
};
You can save a lot of data within a single cookie and return it as an array, try this
function setCookie(cookieKey, cookieValue) {
var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
var idPurchase = cookie.split(",")
idPurchase.push(cookieValue)
document.cookie = cookieKey+"=" + idPurchase
console.log("Id das compras efetuadas :",idPurchase)
$("#purchases_ids option:last").after($('<option onclick="document.getElementById("input_class1").value='+cookieValue+'" value="'+cookieValue+'">'+cookieValue+'</option>'))
}
checkCookie()
function checkCookie() {
var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)idpurchase\s*\=\s*([^;]*).*$)|^.*$/, "$1")
var idPurchase = cookie.split(",")
console.log("Id das compras efetuadas :",idPurchase)
for (i = 1; i < idPurchase.length; i++) {
$("#purchases_ids option:last").after($('<option value="'+idPurchase[i]+'">'+idPurchase[i]+'</option>'))
}
purchases_ids.addEventListener("change",changeSpeed)
}
in this project that I created I store values in arrays, codePen is not allowing the storage of cookies, but in the example below you can get a complete picture, just study the implementation
Github project
Open in Gitpod