how to get value from cookie in javascript - javascript

What i Need:
i Need to use user and evnt_id from cookie.
document.cookie
string :
" country=India; countryCode=IN; __gads=ID=369fde524de77341:T=1417077062:S=ALNI_MakhfG3fYeRIwt9Uw4xSUE8m-2hHw; fbm_172404889604820=base_domain=.10times.com; PHPSESSID=4e467l46efdmvc9vktknod85b2; evnt_id=9; industry=74; evnt_name=India International Trade Fair; evnt_url=iitf; km_ai=jE0JIU3hamljHh0DrWRC%2FR50QNI%3D; km_lv=x; __zlcmid=SAeGECzmK8Nrve; user_flag=2; user=13530767; _ga=GA1.2.1767513107.1417003918; linkedin_oauth_ro57ogahnixy_crc=null; km_uq=; kvcd=1418207265523; _ga=GA1.3.342868374.1416999745; id=13530767; email=afeef1915%40yahoo.com; name=Mohd+Afeef; image_flag=http%3A%2F%2Fgraph.facebook.com%2F100001729894039%2Fpicture".
i need to fetch
user.
event_id from cookie.
code i have tried :
function setCookie(key, value) {
var expires = new Date();
expires.setTime(expires.getTime() + 31536000000); //1 year
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
setCookie('evnt_id','evnt_id');
alert(getCookie('evnt_id'));
problem im facing im not able to fetch user and event_id from cookie.
im using symphony framework and need to implement in twig file.

This problem has been solved before. Don't reinvent the wheel :)
I would advise you to read up on cookies: http://www.quirksmode.org/js/cookies.html
The code below comes from that article.
function 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;
}
console.log(readCookie('evnt_id')); //9
console.log(readCookie('user')); //13530767

Related

Set cookie with array() in jquery

I would like to be able to check if a cookie (id) is set or not: if not set, then create it. If set, retrieve the value (= an array). How can I retrieve the array from the cookie?
I hear that I would have to use JSON, but I'm not sure how that would work with the following code?
function start(id){
if (document.cookie.indexOf('id') === -1 ) {
setCookie('id', id, 7);
}
else {
var playedID = [GET COOKIE ARRAY]
playedID.push(id);
setCookie('id',playedID);
}
}
Here's a way to do it based on some helper functions to make sure you are parsing and stringifying the cookie correctly.
getCookie and setCookie are from https://www.w3schools.com/js/js_cookies.asp
// This won't run due to security policies on this site, but you can run it in the dev tools and see.
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 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 + ";path=/";
}
function getCookieArray(cname) {
var cookie = getCookie(cname);
return cookie ? JSON.parse(cookie) : [];
}
function pushToCookieArray(cname, cvalue, exdays) {
var cookieArray = getCookieArray(cname);
cookieArray.push(cvalue);
setCookie(cname, JSON.stringify(cookieArray), exdays);
}
function start(id) {
pushToCookieArray('id', id, 7);
console.log(getCookieArray('id'));
}
start(5);
start(6);
start(8);
First a cookie is not stored as an array but a string : if you type document.cookie in you console, you will get all the cookies from the website you are visiting, separated with a coma.
So as explained here : https://www.w3schools.com/js/js_cookies.asp,
you will have to create a custom function to access the cookie you need.
Then the value of you cookie is still a string, so as explained here if you want to save an array of ids, you have to use JSON.stringify to encode you array as a string : I want to store Javascript array as a Cookie
You can then create it or update its value :
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 setCookie(cname, cvalue) {
document.cookie = cname + "=" + cvalue + ";";
}
function start(id){
if (getCookie('id') === '' ) {
setCookie('id', JSON.stringify([+id]));
}
else {
let ids = JSON.parse(getCookie('id'))
console.log(ids)
ids.push(+id);
setCookie('id', JSON.stringify(ids));
}
}
function sendID(id) {
console.log(document.getElementById("user-id").value)
start(id);
alert(getCookie("id"))
}
Here is a working example : https://codepen.io/adrientiburce/pen/ExVbYWy?editors=1010

How do I display cookies on other pages?

I am learning about cookies and JavaScript for a student project and have attempted to use them in a school project. However, I have stumbled onto a problem when I try to implement a simple function which bookmarks articles.
This is the code which I place in an article. When I press the bookmark icon, the function below is triggered, creating a cookie that expires after 14 days.
<script>
function showBookmark() {
document.getElementById("bookmark").innerHTML = "bookmark";
var d = new Date();
d.setTime(d.getTime() + (14*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = "cookie1" + "=" + "Article 1 - Title Of Article 1" + ";" + expires + ";path=/";
};
</script>
This is the code which I place in the page where I store and display all the bookmarks the user has made. The code scans through 20 cookies ("cookie1", "cookie2" to "cookie20") and then displays the first 10 cookies where there is a value. The cookies are then displayed in a table using innerHTML().
<script>
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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);
} else {
return "false"
}
}
};
var counter=0;
for (var alpha=0; alpha<20; alpha++){
bookmark = getCookie("cookie"+alpha.toString());
if (counter > 10){
break;
}
if (bookmark != "false"){
document.getElementById("bookmark"+counter.toString()).innerHTML = bookmark;
counter++;
}
};
</script>
However, for some reason the code above does not display the intended result (the name of the article does not appear on the page with all the bookmarks even after pressing the icon and triggering the getCookie function). Is there something wrong with my code?
(This is the first question I am asking so any advice would be greatly appreciated)

how to know if a user has a certain cookie using javascript

I have been stuck on this problem for a couple hours now, and cant seem to get off of it. I have a html website where i'm giving a user a cookie called "schoolid" and it has the school's ID in it. If a user has a certain school ID, in this case "gms08",they will be redirected to another website. This is what i have so far in the cookie area.
I have a check cookie function checking to make sure the user has it, but i cant seem to get it to pick up on the fact that the user has the cookie and it is gms08.
i.stack.imgur.com/wQjnx.png
Pastebin: http://pastebin.com/Gfjc7iTG
<script>
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 + ";path=/";
}
</script>
<script>
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 "";
}
</script>
<script>
function checkCookie() {
var id = getCookie("schoolid");
if (id != "") {
alert("Welcome again ");
} else {
alert("user");
}
}
</script>

Getting value from a cookie

I have set a cookie using the following and it works well. I can see it in browser cookie(console).
But how can i get back the value from cookie ??
days = 1;
cookiename = 'uid';
cookieValue = result.pp.uid;
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 = cookiename + "=" + cookieValue + expires + "; path=/";
I have the following code , but i dont want to use the function.
function 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;
}
Ive no idea of how they are getting the value of cookie..
Is there a simple way like document.cookie ?
Try this library
https://github.com/carhartl/jquery-cookie
Also see this SO post
How do I set/unset cookie with jQuery?
Example from their docs
Read cookie:
$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined

Check if its users first time on site using Javascript

I am trying to find out if its the users first time on my webpage. I am currently storing a variable in local storage and checking if its null or not but it doesn't seem to work in Internet Explorer. What other method can I use to accomplish this?
var str_count = localStorage.getItem("count");
if (str_count == null || str_count == "null")
{
// Do something
}
Setting cookie with long expiration date is definitely more reliable that using localStorage as it is not yet supported by older browsers.
Check this code:
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=/";
}
function 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 eraseCookie(name) {
createCookie(name,"",-1);
}
Read more about cookies here.
You can set a cookie with
document.cookie = name + "=" + value + "; expires=" + exp + "; path=/";
More info here: http://www.w3schools.com/js/js_cookies.asp
More info here: http://www.quirksmode.org/js/cookies.html
As #Greg said, the better solution is to set and get cookie values. Here's two functions to do this:
setCookie = function(){
var args = arguments,
name = (args[0] ? args[0] : '') + '=',
_value = args[1] ? escape(args[1]) : '',
value = _value + ';',
expires = args[2] ? 'expires=' + args[2].toUTCString() + ';' : '',
path = args[3] ? 'path=' + args[3] + ';' : '',
domain = args[4] ? 'domain=' + args[4] + ';' : '',
secure = args[5] ? 'secure;' : '',
newCookie = name + value + expires + path + domain + secure;
document.cookie = newCookie.match(/[a-z||A-Z]/) ? newCookie : ''
return _value;
},
getCookie = function(name){
if(!name || name.replace(/[^a-z|0-9|çáéíóúãõâêîôûàèìòùäëïöü]/,'')=='*') return document.cookie;
var ck = ' ' + document.cookie + ' ',
pos = ck.search(' ' + name + '='),
pos = (pos!=-1) ? pos + 1 : ck.length,
ck = ck.substring(pos-1,ck.length),
end = (ck.search('; ')!=-1) ? ck.search('; ') : ck.length,
value = ck.substring(((ck.search('=')!=-1) ? (ck.search('=')+1) : end),end);
return unescape((value[value.length-1]==' ') ? value.substring(0,value.length-1) : value);
}
They're crossbrowser functions. To use getCookie function, just use the name parameter, and with the setCookie function, use the name,value,expires,path,domain,secure parameters

Categories