Create Cookie Array that never expires with JS/JQuery? - javascript

I have a website with quotes and want users to be able to favourite quotes clicking on a star-icon. I have this code:
jQuery('.fav').click(function(event) {
event.preventDefault();
$this = $(this).parent();
var id = $this.attr("data-id");
// Build the expiration date string:
var expiration_date = new Date();
var cookie_string = '';
expiration_date.setFullYear(expiration_date.getFullYear() + 1);
// Build the set-cookie string:
cookie_string = "fav="+id+"; path=/; expires=" + expiration_date.toGMTString();
// Create/update the cookie:
document.cookie = cookie_string;
});
But this only saves one cookie "fav=id". I wanted to create a cookie array where all quotes that will be clicked are saved with their id in the cookie array "fav", so I could show a list to the user of all saved quotes. How could I accomplish this?

to write the array
var cookieArray= {};
cookieArray[id] = true; //or whatever value
var stringifiedArr = JSON.stringify(cookieArray);
$.cookie("favs",stringifiedArr , { path: '/' });
to read the cookie
var arrFromCookie = $.cookie("favs");
var favsCookieData = JSON.parse(arrFromCookie);

Use the JSON.stringify() and JSON.parse() methods to store an array or an object as a string in the cookie and to retrieve it later.

Cookies only can hold as strings. If I would like to simulate an array I will to serialize it and deserialize it. Can use Json library

Related

How to make use of URL that was saved in cookie?

I am saving a URL in a cookie using Angular
$cookies.put("targetURL": "http://partners.api.xyz.net/apiservices/deeplink/v2?_cje=TmvlUQgTj%2fbxOQ%2bkXy5haJR9JWcHT9aaSjEP%2fEbwSq4uZqOYt%2fRV9FYsU1PT80PD&url=http%3a%2f%2fwww.apideeplink.com%26cabin_class%3deconomy%26facilitated%3dfalse%26ticket_price%3d72.82%26is_npt%3dfalse%26is_multipart%3dfalse%26client_id%3d2017-02-22T10%3a02%3a07")
However, I have to retrieve this cookie with plain javascript. When I try to get it, the string is transformed into
"http%3A%2F%2Fpartners.api.xyz.net%2Fapiservices%2Fdeeplink%2Fv2%3F_cje%3DTmvlUQgTj%252fbxOQ%252bkXy5haJR9JWcHT9aaSjEP%252fEbwSq4uZqOYt%252fRV9FYsU1PT80PD%26url%3Dhttp%253a%252f%252fwww.apideeplink.com%2526cabin_class%253deconomy%2526facilitated%253dfalse%2…e%2526is_multipart%253dfalse%2526client_id%253d2017-02-22T10%253a02%253a07" and not clickable anymore.
To retrieve the cookie I am using the function:
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
Why is the string changed like this and what can I do to solve this?
You need to decode the URI with decodeURIComponent()
old = "http%3A%2F%2F";
new = decodeURIComponent( old );
#new => http://

Removing parameter values of a url in the next page using javascript only

I need to remove the values from the url after the ? in the next page the moment i click from my first page. I tried a lot of coding but could not get to a rite path. Need help.
The strings ex- Name, JobTitle and Date are dynamically generated values for ref.
Below are the links associated with the code:
Required url
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?
Resultant url:
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
listItem.onclick = function(){
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
//window.location.href = window.location.href.replace("ListCandidateNew", "newOne") + "?" + stringParameter;
window.location.href="file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?"
+ stringParameter;
}
This should work:
var url = file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
var index = url.lastIndexOf("?");
url = url.slice(0, index+1); // index+1 so that "?" is included
Thanks everond for trying and attempting to answer my problem. Well, i have found the solution using window.sessionStorage as i wanted by keeping the string parameter alive to pass the values. Here is the full code:
I have two pages for passing the value from one to another: ListCandidateNew.html and newOne.html
ListCandidateNew.html
listItem.onclick = function()
{
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
window.sessionStorage['Name'] = elementData.name;
window.sessionStorage['JobTitle'] = elementData.job_title;
window.sessionStorage['Date'] = elementData.entered_date;
**newOne.html**
function LoadCandidateDetail()
{
document.getElementById('Name').innerHTML = window.sessionStorage['Name'];
document.getElementById('JobTitle').innerHTML = window.sessionStorage["JobTitle"];
document.getElementById('Date').innerHTML = window.sessionStorage["Date"];
}

Path of Cookie not working

I want to create a cookie to store a class so I can use this through the whole site. I checked the cookies, and the cookie is created. The problem is when the cookie is set on another page the path is /url-page en not /
jQuery(document).ready(function($) {
values = $.map($('select option'), function(e) { return e.value; });
$('#color-select').on('change', function() {
$("body").removeClass(values.join(" ")).addClass( ("" + $('#color-select').val()) );
var foobar =("" + $('#color-select').val());
document.cookie = "gsscookie=" + foobar, "expires=;domain=;path=/";
})
});
I'm working on a local dev environment with the url plastic.dev.local. What am I doing wrong?
The value that gets assigned to document.cookie should be a single string, with a semicolon after the "key=value" assignment, and then semicolons between each property that you're setting on the cookie. The way you're doing it, with the comma after the first string, makes it so the second string is basically ignored. If you change it to document.cookie = "gsscookie=" + foobar + ";expires=;domain=;path=/";, it should work.

How to store every content of an array in cookie [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to store an array in jquery cookie?
How to store every content of an array in cookie in javascript and also i have to retrive all the term of an array?
I tried but i am not able to retrive items back from cookie....
My code is below wat i tried
var myArray=["123","234","32"];
$.cookie('myCookie', escape(myArray), { expires: 1});
var s = unescape($.cookie('myCookie');
Using JQuery, you can use serialize function to retrieve all data in string : http://api.jquery.com/serialize/
To create a cookie in JavaScript you must assign a string to document.cookie.
It takes values in a name = value format e.g.
document.cookie = 'data=hello; max-age=60; path=/; domain=yoursite.com';
The best way to store an array in here is to use JSON and the method JSON.stringify():
var arr = ['hello', 'goodbye', 'au revoir'];
document.cookie = 'data=' + escape(JSON.stringify(arr)) + '; max-age=60; path=/; domain=yoursite.com'
(Note a cookie must be <= 4KB)
Retrieving the cookie is a little harder as it is a string, so I borrowed this function which searches the string for your cookie name then returns it's value:
// Source: http://www.thesitewizard.com/javascripts/cookies.shtml
function get_cookie ( cookie_name )
{
var cookie_string = document.cookie ;
if (cookie_string.length != 0) {
var cookie_value = cookie_string.match (
'(^|;)[\s]*' +
cookie_name +
'=([^;]*)' );
return decodeURIComponent ( cookie_value[2] ) ;
}
return '' ;
}
In our example you would use it like this:
var cookie = get_cookie('data');
var arr = JSON.parse(cookie); // Convert JSON string back into array
Note I use JSON.parse() to convert the JSON string back into a JavaScript array.
For more information on utilising cookies in JavaScript I suggest you read: http://www.thesitewizard.com/javascripts/cookies.shtml

Read a javascript cookie by name

I have set a cookie using
document.cookie =
'MYBIGCOOKIE=' + value +
'; expires=' + now.toGMTString() +
'; path=/';
Now there are between 5 and 10 cookies set on this site, is there a way to check the value ofthis cookie by name.
if (document.cookie.MYBIGCOOKIE == '1') {
alert('it is 1')
}
Use the RegExp constructor and multiple replacements to clarify the syntax:
function getCook(cookiename)
{
// Get name followed by anything except a semicolon
var cookiestring=RegExp(cookiename+"=[^;]+").exec(document.cookie);
// Return everything after the equal sign, or an empty string if the cookie name not found
return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
}
//Sample usage
var cookieValue = getCook('MYBIGCOOKIE');
Unfortunately, Javascript's cookie syntax is nowhere near as nice as that. In fact, in my opinion, it's one of the worst designed parts.
When you try to read document.cookie, you get a string containing all the cookies set. You have to parse the string, separating by the semicolon ; character. Rather than writing this yourself, there are plenty of versions available on the web. My favourite is the one at quirksmode.org. This gives you createCookie, readCookie and deleteCookie functions.
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Source: W3Schools
Edit: as #zcrar70 noted, the above code is incorrect, please see the following answer Javascript getCookie functions
You can use the following function:
function getCookiesMap(cookiesString) {
return cookiesString.split(";")
.map(function(cookieString) {
return cookieString.trim().split("=");
})
.reduce(function(acc, curr) {
acc[curr[0]] = curr[1];
return acc;
}, {});
}
When, called with document.cookie as parameter, it will return an object, with the cookies keys as keys and the cookies values.
var cookies = getCookiesMap(document.cookie);
var cookieValue = cookies["MYBIGCOOKIE"];
using jquery-cookie
I find this library helpful. 3.128 kb of pure convenience.
add script
<script src="/path/to/jquery.cookie.js"></script>
set cookie
$.cookie('name', 'value');
read cookie
$.cookie('name');
One of the shortest ways is this, however as mentioned previously it can return the wrong cookie if there's similar names (MyCookie vs AnotherMyCookie):
var regex = /MyCookie=(.[^;]*)/ig;
var match = regex.exec(document.cookie);
var value = match[1];
I use this in a chrome extension so I know the name I'm setting,
and I can make sure there won't be a duplicate, more or less.
document.cookie="MYBIGCOOKIE=1";
Your cookies would look like:
"MYBIGCOOKIE=1; PHPSESSID=d76f00dvgrtea8f917f50db8c31cce9"
first of all read all cookies:
var read_cookies = document.cookie;
then split all cookies with ";":
var split_read_cookie = read_cookies.split( ";" );
then use for loop to read each value. Into loop each value split again with "=":
for ( i = 0; i < split_read_cookie.length; i++ ){
var value = split_read_cookie[i];
value = value.split( "=" );
if( value[0] == "MYBIGCOOKIE" && value[1] == "1" ){
alert( 'it is 1' );
}
}
The point of Stack Overflow is to provide a database of good quality answers, so I am going to reference some standard source code and an article that gives examples:
http://www.codelib.net/javascript/cookies.html
Note: The code is regular-expression free for greatly enhanced efficiency.
Using the source code provided, you would use cookies like this:
makeCookie('color', 'silver');
This saves a cookie indicating that the color is silver. The cookie would expire after the current session (as soon as the user quits the browser).
makeCookie('color', 'green', { domain: 'gardens.home.com' });
This saves the color green for gardens.home.com.
makeCookie('color', 'white', { domain: '.home.com', path: '/invoices' });
makeCookie('invoiceno', '0259876', { path: '/invoices', secure: true });
saves the color white for invoices viewed anywhere at home.com. The second cookie is a secure cookie, and records an invoice number. This cookie will be sent only to pages that are viewed through secure HTTPS connections, and scripts within secure pages are the only scripts allowed to access the cookie.
One HTTP host is not allowed to store or read cookies for another HTTP host. Thus, a cookie domain must be stored with at least two periods. By default, the domain is the same as the domain of the web address which created the cookie.
The path of an HTTP cookie restricts it to certain files on the HTTP host. Some browsers use a default path of /, so the cookie will be available on the whole host. Other browsers use the whole filename. In this case, if /invoices/overdue.cgi creates a cookie, only /invoices/overdue.cgi is going to get the cookie back.
When setting paths and other parameters, they are usually based on data obtained from variables like location.href, etc. These strings are already escaped, so when the cookie is created, the cookie function does not escape these values again. Only the name and value of the cookie are escaped, so we can conveniently use arbitrary names or values. Some browsers limit the total size of a cookie, or the total number of cookies which one domain is allowed to keep.
makeCookie('rememberemail', 'yes', { expires: 7 });
makeCookie('rememberlogin', 'yes', { expires: 1 });
makeCookie('allowentergrades', 'yes', { expires: 1/24 });
these cookies would remember the user's email for 7 days, the user's login for 1 day, and allow the user to enter grades without a password for 1 hour (a twenty-fourth of a day). These time limits are obeyed even if they quit the browser, and even if they don't quit the browser. Users are free to use a different browser program, or to delete cookies. If they do this, the cookies will have no effect, regardless of the expiration date.
makeCookie('rememberlogin', 'yes', { expires: -1 });
deletes the cookie. The cookie value is superfluous, and the return value false means that deletion was successful. (A expiration of -1 is used instead of 0. If we had used 0, the cookie might be undeleted until one second past the current time. In this case we would think that deletion was unsuccessful.)
Obviously, since a cookie can be deleted in this way, a new cookie will also overwrite any value of an old cookie which has the same name, including the expiration date, etc. However, cookies for completely non-overlapping paths or domains are stored separately, and the same names do not interfere with each other. But in general, any path or domain which has access to a cookie can overwrite the cookie, no matter whether or not it changes the path or domain of the new cookie.
rmCookie('rememberlogin');
also deletes the cookie, by doing makeCookie('rememberlogin', '', { expires: -1 }). This makes the cookie code longer, but saves code for people who use it, which one might think saves more code in the long run.
I use this to read cookie:
function getCookie (key) {
let value = ''
document.cookie.split(';').forEach((e)=>{
if(e.includes(key)) {
value = e.split('=')[1]
}
})
return value
}
let name = getCookie(name)
Using string.match. Returns the cookie or null
function checkForCookie(name) {
let cookieString = document.cookie.match(name + '=[^;]+')
return cookieString ? cookieString[0] : cookieString
}
Here is an example implementation, which would make this process seamless (Borrowed from AngularJs)
var CookieReader = (function(){
var lastCookies = {};
var lastCookieString = '';
function safeGetCookie() {
try {
return document.cookie || '';
} catch (e) {
return '';
}
}
function safeDecodeURIComponent(str) {
try {
return decodeURIComponent(str);
} catch (e) {
return str;
}
}
function isUndefined(value) {
return typeof value === 'undefined';
}
return function () {
var cookieArray, cookie, i, index, name;
var currentCookieString = safeGetCookie();
if (currentCookieString !== lastCookieString) {
lastCookieString = currentCookieString;
cookieArray = lastCookieString.split('; ');
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
name = safeDecodeURIComponent(cookie.substring(0, index));
if (isUndefined(lastCookies[name])) {
lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
};
})();
This is my simple solution:
function getCookieValue(userKey){
let items = document.cookie.split(";")
for(item of items){
let [key, value] = item.split("=");
if(key === userKey)
return value;
};
return null;
}
I have come up with confusing yet very simple step after 2 hrs of concentration.
suppose a cookie 'username' is stored with a value 'John Doe'.
Then call readCookies('username'), this function (defined just below ) returns the value 'John Doe'.
function readCookies(requestedKey){
var cookies = document.cookie;
var temporaryKeyIndex=-1,temporaryKeySet=false,temporaryKey,temporaryValue;
var temporaryValueIndex = -1,previousTemporaryValueIndex=-2;
var readableCookie=[];
var a;
for(var i=0;i<cookies.length;i++){
if(cookies[i]!='='&&!temporaryKeySet){
temporaryKeyIndex++;
temporaryValueIndex++;
}
else{
temporaryKeySet = true;
if(cookies[i]==';'||i==(cookies.length-1)){
temporaryKey = cookies.slice(previousTemporaryValueIndex+2,temporaryKeyIndex+1);
if(cookies.length>temporaryValueIndex+2){
temporaryValue = cookies.slice(temporaryKeyIndex+2,temporaryValueIndex+1);
}
else{
temporaryValue = cookies.slice(-((cookies.length-1) - (temporaryKeyIndex+1)))
}
alert('tempkey: '+temporaryKey+', reqKEY: '+requestedKey);
if(requestedKey.trim()==temporaryKey.trim()){
alert(1);
return temporaryValue;
}
previousTemporaryValueIndex = temporaryValueIndex;
temporaryKeyIndex = ++temporaryValueIndex;
temporaryKeySet=false;
}
else{
temporaryValueIndex++;
}
}
}
}
Here is an API which was written to smooth over the nasty browser cookie "API"
https://github.com/jaaulde/cookies
The simplest way to read a cookie I can think is using Regexp like this:
**Replace COOKIE_NAME with the name of your cookie.
document.cookie.match(/COOKIE_NAME=([^;]*);/)[1]
How does it work?
Cookies are stored in document.cookie like this: cookieName=cookieValue;cookieName2=cookieValue2;.....
The regex searches the whole cookie string for literaly "COOKIE_NAME=" and captures anything after it that is not a semicolon until it actually finds a semicolon;
Then we use [1] to get the second item from array, which is the captured group.

Categories