Written this piece of Code to pass array into Cookie
<script>
var products = [];
{
var products = [{
'name': '$1 Silver Membership Trial - Silver-Membership-3-Month',
'price': '279.88',
'quantity': 1
}]
}
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=/";
}
createCookie('products', JSON.stringify(products));
createCookie('revenue', 279.88);
</script>
When trying to this piece Code in Console does not get array value
console.log(JSON.stringify(createCookie.get('products')));
To get all cookies for the current domain you can use document.cookie.
If you want to get a specific cookie, you must work with that string and extract it.
You can use this function to get a cookie buy it's name:
function getCookieByName(cookiename) {
const cookieString = RegExp(cookiename + "=[^;]+").exec(document.cookie);
return decodeURIComponent(!!cookieString ? cookieString.toString().replace(/^[^=]+./, '') : '');
}
and then just call it like this:
console.log(getCookieByName('products'));
Related
In that case, I put 1 2 3 in each input and it only shows number 3. How can I fix it? I'm sorry if it's a stupid question but I really don't know.
function WriteCookie()
{
cookievalue= document.myform.firstname.value+";";
cookievalue1= document.myform.memory.value+";";
cookievalue2= document.myform.half.value+";";
cookievalue3= document.myform.lose.value+";";
document.cookie=cookievalue;
document.cookie=cookievalue1;
document.cookie=cookievalue2;
document.cookie=cookievalue3;
alert(document.cookie);
}
You rewrote document.cookie 4 times with a new value each time.
If you'd like to combine data from all 4 vars uses code like:
function WriteCookie()
{
var cookievalue = document.myform.firstname.value+";";
var cookievalue1 = document.myform.memory.value+";";
var cookievalue2 = document.myform.half.value+";";
var cookievalue3 = document.myform.lose.value+";";
cookievalue = cookievalue + cookievalue1 + cookievalue2 + cookievalue3;
document.cookie = cookievalue;
alert(document.cookie);
}
For last two weeks I was working on saving a page id in cookies and then retrieve it in some other page.
Finally I solved it but now I have some other problem I want to use this id (the one I saved in cookie and retrieve it) in my php code .
I know javascript is client side code and php is server side code but I have to do this. Please help me out with this.
This is my javascript code which is working great and I get the saved id with this line "+value.favoriteid+"
<script>
/*
* 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(){
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);
}
$(document.body).on('click','#addTofav',function(){
var fav = {'favoriteid':favID};
faves.push(fav);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
var myfaves = JSON.parse(readCookie('favespages'));
if(myfaves){
faves = myfaves;
} else {
faves = new Array();
}
$.each(myfaves,function(index,value){
var element = '<li class="'+index+'"><h4>'+value.favoriteid+'</h4> ';
$('#appendfavs').append(element);
});
});
</script>
Read cookie on php side it is easiest thing after you set them by js.
Any cookies sent to you from the client will automatically be included
into a $_COOKIE auto-global array if variables_order contains "C". If
you wish to assign multiple values to a single cookie, just add [] to
the cookie name.
Depending on register_globals, regular PHP variables can be created
from cookies
Here php are some examples:
<?php
echo $_COOKIE["your cookie name"];
?>
<?php
print_r($_COOKIE);
?>
It's not recommended to rely on them as this
feature is often turned off for the sake of security.
http://php.net/manual/en/features.cookies.php
If you already managed to save to cookie in javascript, then it should be no problem to retrive it in PHP, just use $_COOKIE["COKKIE_NAME"] (Where you ofcourse change COOKIE_NAME, to the name of the cookie you saved in JS)..
Have a look at http://php.net/manual/en/features.cookies.php for more examples.
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
I am developing an application using jQuery that uses cookies. Right now, it is located at application.html on my PC desktop.
However, I cannot store and retrieve a cookie. I had included jquery-1.7.1.min.js, json2.js, and jquery.cookie.js in my HTML file in that order.
Here is how I am storing a cookie to last for 7 days:
$.cookie("people", JSON.stringify(people_obj_array), {expires: 7});
The global array people_obj_array looks like
[
{
"name": "Adam",
"age": 1,
},
{
"name": "Bob",
"age": 2,
},
{
"name": "Cathy",
"age": 3,
},
]
When I test JSON encryption with alert(JSON.stringify(people_obj_array)), it looks fine:
However, when I retrieve this cookie via:
alert($.cookie("people"));
before even refreshing the page, an alert pops up that reads "null." Shouldn't the text be the alert JSON string? Am I using the JQuery cookies library correctly?
Just to clarify, here is how I am testing:
$.cookie("people", JSON.stringify(people_obj_array), {expires: 7}); // store
alert($.cookie("people")); // attempt to retrieve
I have Firebug, and I am willing to do some Console tests.
It's probably the fact the file is on your desktop that's causing the problem. Browsers normally behave by serving up cookies based on the domain they were received from and their path.
You may not be able to read the cookie immediately after setting it: Writing a cookie involves setting headers in a HTTP request and, likewise, reading them involves reading headers in a HTTP response.
Try hosting your page on a web-server and see if that works for you.
If you are having troubles with the cookies plugin why not just make up your own cookie functions? Read, Write and (optional) delete.
var createCookie = function(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=/';
};
var readCookie = function(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 eraseCookie = function(name) {
createCookie(name, '', -1);
};
I cannot comment on the specific plugin as I have never used it.. however these functions all work and have been tested.
So for your example:
createCookie("people", JSON.stringify(people_obj_array), 7); // store
alert(readCookie("people")); // retrieve
eraseCookie("people"); // remove
alert(readCookie("people")); // oo look i'm no longer here.
From my research jquery.cookie.js is fairly old, and doesn't seem to be maintained any longer. You might have better luck using this library instead. Its description on Google Code is "Javascript Cookie Library with jQuery bindings and JSON support", and includes methods for everything you're trying to do!
I've been out of web development for a while now so very rusty.
I need to make a cookie
If the user visits the site > set cookie
If user comes back to site > read cookie
If time since user last arrived is less than 24hrs > set the ID of a div to style="display:none;"
im struggling and would really appreciate some guidance.
thanks so much
With JavaScript you can
- read cookie:
var coo = [],
a;
if(document.cookie != ''){
$.each(document.cookie.split('; '), function(i, val){
a = val.split('=');
coo[a[0]] = a[1];
});
}
here we have a coo with all cookies (coo['Cookie1'] == 'value').
- set cookie:
document.cookie = 'Cookie_1='+'value for this cookie';
BTW code is using jQuery for $.each.
Heres the messy solution i cam up with in case anyone wanted to know:
function nameDefined(ckie,nme)
{
var splitValues
var i
for (i=0;i
tvalue=getCookieValue(nvpair,cname) //Gets the value of the cookie
if (tvalue == cvalue) return true
else return false
}
else return false
}
function redirectLink() {
if (testCookie("here10", "yes")) {
//window.location="here.html" //Go to the location indicating the user has been here
//alert("there");
window.document.getElementById("indicator").style.display = "none";
}
else{
//alert(" not there");
var futdate = new Date() //Get the current time and date
var expdate = futdate.getTime() //Get the milliseconds since Jan 1, 1970
expdate += 10000 //expires in 1 hour(milliseconds)
futdate.setTime(expdate)
var newCookie="here10=yes; path=/;" //Set the new cookie values up
newCookie += " expires=" + futdate.toGMTString()
window.document.cookie=newCookie //Write the cookie
// window.location="not.html" //Go to the location indicating the user has not been here
window.document.getElementById("indicator").style.display = "block";
}
}