Create an array of id's in cookie JS - javascript

I want to update the cookie from my WP page with the post id's that the user is visiting. But my problem is that each time the value from the array is deleted and the array contains always just on id, and the next id's are just overwited.
let post_id = my_script_vars.postID; // this is a variable with some id's
let arr = [] // i create an array
function setCookie(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=/";
}
index = arr.indexOf(post_id);
if (index == -1) { // if the id is not in the array the push it
arr.push(post_id);
} else { // if it is in array then keep all of them
arr.splice(index, 1);
}
setCookie("id_film",JSON.stringify(arr),30);
and i want my array to keep all the id's and not just one.

Follow these steps:
Don't create your arr variable until you need it
Add a function to read cookie and return contents as JSON
On page load, read the cookie, update your array, then save new contents
Final code should see like this:
let post_id = my_script_vars.postID; // this is a variable with some id's
function setCookie(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 to read cookie and return as JSON
function getCookie(name) {
let a = `; ${document.cookie}`.match(`;\\s*${name}=([^;]+)`);
return a ? JSON.parse(a[1]) : [];
}
// Be sure to execute after DOM is loaded
window.addEventListener('load', function() {
// Get saved IDs
let arr = getCookie('id_film');
index = arr.indexOf(post_id);
if (index == -1) {
// if the id is not in the array the push it
arr.push(post_id);
}
setCookie("id_film",JSON.stringify(arr),30);
});

Related

Capture the values ​of a cookie before the page finishes loading

How can I capture the value of a cookie before the page finishes loading ? This is my code in JavaScript
window.addEventListener('load', () => {
var start_date = document.getElementById('start-date').value;
var end_date = document.getElementById('end-date').value;
var field = document.querySelectorAll('.gform-filter-field')[0].value;
var operator = document.querySelectorAll('.gform-filter-operator')[0].value;
var filter = document.querySelectorAll('.gform-filter-value')[0].value;
console.log(start_date);
console.log(end_date);
console.log(field);
console.log(operator);
console.log(filter);
// Creating a cookie after the document is ready
createCookie("start_date", start_date, "10");
createCookie("end_date", end_date, "10");
createCookie("field", field, "10");
createCookie("operator", operator, "10");
createCookie("filter", filter, "10");
// Function to create the cookie
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.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" +
escape(value) + expires + "; path=/";
}
alert( start_date );
})
These variables I have to capture in my PHP file. This is my code in PHP
add_filter( 'gravityflow_search_criteria_status', 'sh_status_search_criteria', 10, 1 );
function sh_status_search_criteria( $search_criteria ) {
if (empty($_COOKIE["start_date"]))
{
echo 'The variable is empty, its content is: '.$_COOKIE["start_date"];
}
else{
echo 'The variable is not empty, its content is: '.$_COOKIE["start_date"];
}
/*if(($_SERVER['REQUEST_URI'] == '/registro/') || ($_SERVER['REQUEST_URI'] == '/registro/?entry-id&start-date='.$_COOKIE["start_date"].'&end-date&form-id=1&f[0]&t[0]&v[0]=0&gravityflow-print-timelines=print_timelines&gravityflow-print-page-break=print_page_break'))
{$search_criteria['field_filters'][] = array ('key' => '7', 'operator' => 'is','value' => get_current_user_id() );}
return $search_criteria;
*/
}
The variables are printed after I reload the page. I would like to know if there is a way to print these variables without having to reload the page again.

Is this javascript code valid? And is it efficient? Trying to create a javascript user ID and a session ID

Im trying to create my own analytics script for my website, and for this I have tried to put together a way to create userID and sessionID.
But I am not sure if I have done it correctly.
I'm trying to:
Check to see if user has set a userID - if not set it.
check to see if user has a sessionID - it not set it.
the userID is set to follow the user, where the user continues to hold the userID on several visits, where the sessionID is unique for each visit.
if (getCookie('yb_uid') != null) {
if (getCookie('yb_sid') != null) {
setCookie('yb_uid', getCookie('yb_uid'), 730);
setSessionCookie(getCookie('yb_sid'));
} else {
setCookie('yb_uid', getCookie('yb_uid'), 730);
setSessionCookie(setSID());
}
} else {
setCookie('yb_uid', setUID(), 730);
setSessionCookie(setSID());
}
if (getCookie('yb_sid') == null || getCookie('yb_sid') ==
'undefined' || !getCookie('yb_sid')) {
setSessionCookie(setSID());
}
function setUID() {
return "ybID#" + _setID(5) + "-" + _setID(5) + "-" + Date.now();
}
function setSessionCookie(value) {
var now = new Date();
var minutes = 30;
now.setTime(now.getTime() + (minutes * 60 * 1000));
document.cookie = "yb_sid=" + value + "; max-age=" + now.toUTCString() + "; expires=" + now.toUTCString() + "; path=/";
} /*set session cookie*/
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
} /* get cookie value */
function _setID(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function setSID() {
var ts = Math.round(+new Date() + Math.random() / 1000);
return ts;
}
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
var expires = "; max-age=" + date.toGMTString() + " expires=" + date.toGMTString();
} else {
var expires = "";
}
document.cookie = name + "=" + value + expires + ";path=/";
Maybe this has an even easier way to script it?
Have you tried UUID https://www.npmjs.com/package/uuid for generating an user id?

Javascript set then display a cookie value

My problem seems to be easy but I can't make it work; I want to set a cookie variable called "splash" then display it (later I want use in IF clause)
Here is my code :
<html>
<head>
<script type="text/javascript">
document.cookie = "splash=" + encodeURIComponent("blue theme")
var re = new RegExp(splash + "=([^;]+)");
var value = re.exec(document.cookie);
alert(value);
</script>
</head>
<body>
</body>
</html>
You should change your regex to include splash as part of the quoted string. Even though spash is the variable you're using in the cookie, it does not automatically become a javascript variable.
document.cookie = "splash=" + encodeURIComponent("blue theme")
var re = new RegExp("splash=([^;]+)");
var theme = re.exec(document.cookie)[1];
re.exec returns an array. the first element is the entire matched string (including splash=). The second is your capture group (blue%20theme).
Use Following function to set and get Cookie
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 = "";
}
var fixedName = '';
name = fixedName + name;
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(name)
{
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
function eraseCookie(name)
{
createCookie(name, "", -1);
}

Cuts off form data when setting url as value

This script creates a cookie depending on form data, (ex: ?docname=My Document)
<script type="text/javascript">
{
var docname = getValue("docname"); // these go off another script to get form data
var save = getValue("save");
var url = window.location.href;
}
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=/";
}
function saveDoc() {
if (docname != '') {
setCookie(docname,url,730);
}
else {
// Nothing else to do
}
}
// Helps to find errors if they exist
window.onerror = function(errorMessage, url, line) {
var errorText = 'message: ' + errorMessage + '\nurl: ' + url + '\nline: ' + line + ' please contact us, and report this error.';
alert(errorText);
}
</script>
It creates the cookie and sets the name of it as the docname variable, but when it sets the url as the value, it cuts off the form data.
I've researched and changed the code but couldn't find an answer, can anyone help?
Solution
<script type="text/javascript">
{
var docname = getValue("docname"); // these go off another script to get form data
var save = getValue("save");
var url = window.location.href;
var recode = encodeURIComponent(url);
}
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=/";
}
function saveDoc() {
if (docname != '') {
setCookie(docname,recode,730);
}
else {
// Nothing else to do
}
}
// Helps to find errors if they exist
window.onerror = function(errorMessage, url, line) {
var errorText = 'message: ' + errorMessage + '\nurl: ' + url + '\nline: ' + line + ' please contact us, and report this error.';
alert(errorText);
}
</script>
changed the variable used to set the value to recode and set recode equal to encodeURIComponent(url); so it decodes the url, decoding it and making it possible to have form data in a value or name of a cookie, etc. Thanks to #epascarello
encodeURIComponent() is your friend here
document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
and when you get it, you need to decode it with decodeURIComponent().

preserving the state using javascript and jquery

I having problem figuring howto preserve the present state ...Let say I have selected radio button and checkbox in present form and navigate way to a different page but if I want to go back to old page how should I able to see the selected radio and checkboxes in my previous page..
Well you can use cookies to do the same. here is a small code snippet that acts over cookies:
var myCookieHandler = (function () {
return {
createCookie: function (name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
},
readCookie: function (name) {
var nameEq = name + "=";
var ca = document.cookie.split(';');
var i;
for (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;
},
deleteCookie: function (name) {
this.createCookie(name, null, -1);
}
};
}());
usage:
myCookieHandler .writeCookie("Login","true",2);
var cookieValue=myCookieHandler.readCookie("Login");
myCookieHandler.deleteCookie("Login");
Thus when you come back to this page you read your cookie and do the necessary with the same.
Hope this helps..

Categories