Setting multiple cookies in Javascript - javascript

I'm trying to set multiple cookies in document.cookie, but unfortunately only one is getting added.
I know there are multiple examples present on the 'Net for setting up these kind of cookies,and I followed one of them. But still I'm unable to set that out.
I followed this link to set my cookie.
My Code:
function setCookie(start_time,end_session_time,total_time,flag,count){
var cookie_string = "start_time="+start_time;;
if(end_session_time) {
cookie_string +="; end_session_time="+end_session_time;
}
if(total_time){
cookie_string +="; total_time="+total_time;
}
if(flag){
cookie_string +="; flag="+flag;
}
if(count){
cookie_string +="; count="+count;
}
document.cookie =cookie_string ;
console.log(cookie_string);
console.log("document.cookie ="+ document.cookie);
}
The Output:
cookie_string :: start_time=1369926508266; flag=1; count=1
document.cookie =start_time=1369926508266;

Adding a cookie is performed via document.cookie = "name=value"
to add multiple keys, you should perform multiple assigments
function setCookie(start_time, end_session_time, total_time, flag, count) {
document.cookie = "start_time=" + start_time;
if (end_session_time) {
document.cookie = "end_session_time=" + end_session_time;
}
if (total_time) {
document.cookie = "total_time=" + total_time;
}
if (flag) {
document.cookie = "flag=" + flag;
}
if (count) {
document.cookie = "count=" + count;
}
console.log("document.cookie = " + document.cookie);
}

Cookies are key value pairs (with some optional additional info added on, like the expiry date). To set more than one, you just set document.cookie more than once. The ; separator is used to specify the additional info, not to add more different cookies.

There you go a sample example to add, list and delete multiple cookies
<!DOCTYPE html>
<html>
<head>
<script>
var n=1;
function addCookie(){
document.cookie=n+"="+n;n++;
}
function ListCookies(){
var result = document.cookie;
document.getElementById("p").innerHTML=result;
}
function removeCookies(){
//document.cookie="";
var result = document.cookie;
var cookieArray = result.split(";");
for(var i=0;i<cookieArray.length;i++){
var keyValArr = cookieArray[i].split("=");
document.cookie=keyValArr[0]+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
}
</script>
</head>
<body>
<button onclick='addCookie()'>ADD COOKIE</button><br>
<button onclick='ListCookies()'>LIST COOKIES</button>
<button onclick='removeCookies()'>REMOVE COOKIES</button>
<h1>RESULT:</h1>
<p id="p"></p>
</body>
</html>

Related

Redirecting post to a different page

I'm writing a simple diary application and I'd like the user to input the entry on one page and have some js script take that entry and collect it into a different page ("diary-posts"). With the code below I can only collect posts within the same page however:
<! DOCTYPE html>
<html lang="en">
<body>
<header class="text-center">
<h2>
Diary Posts
</h2>
</header>
<div class="wrapper text-center">
<textarea id="txt" rows="3" placeholder="How's your day?"></textarea>
<div class="text-l">
<button onclick="getRs()">Create</button>
</div>
<div id="rs" class="wrapper"></div>
<script src="diary-script.js"></script>
</body>
</html>
function _(id){
return document.getElementById(id)
}
function getRs() {
let txt = _('txt').value
const d = new Date()
_('rs').innerHTML += `<div class="card"><p>${txt}</p>
<small>${d.toLocaleTimeString()}, ${d.toLocaleDateString()}</small></div>`
}
How can I modify this in a simple way to achieve what I want?
There is a lot of ways but I recommend you these options. Choose the best one that works for you.
1. Cookie
This option is best if you want it to use in backend too, because you send cookies data to the backend by every requests. so the data must NOT be too large and must be needed in the backend. otherwise you should use the "localStorage".
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 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 "";
}
setCookie("name", value, 1) //set the cookie for 1 day
getCookie("name") //get the cookie everywhere you want
2. localStorage
If you want to use it only in the user device, this is the option you wanna pick.
note: localStorage stores the data with no expiration date. the data will never ever will be deleted automatically unless you delete it or the user delete it by browser settings.
localStorage.setItem("fieldName", data); //set the item
localStorage.getItem("fieldName"); //get the item
3. sessionStorage (recommended)
sessionStorage is similar to localStorage but the difference is that this will be deleted when user close the browser. so if the data is not so much important and you don't need it next time the user visits the page, this option is made for you.
sessionStorage.setItem("fieldName", data); //set the data
sessionStorage.getItem("fieldName"); // get the data
4. Use backend
you can also store the data in database via backend. you can use an API to send the data to the backend. this option is good for when you need the data in backend and you always need it.

How to make webpage that remembers the choices made via javascript change attributes?

Hello , This is the code that can change the image src and I am using it offline .It has 2 button , one of which turns on the light and other turns off it. It works well! But problem is it doesn't remember the choice i made once i reload the page. Ex. If i turn on the light , it shows the glowing bulb but forgets after reload.
Note: I have tried some online solutions but since it was about something related to javascript, it didn't seem to work.
Target is chrome only!
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attributes.</p>
<p>In this case JavaScript changes the src (source) attribute of an image.
</p>
<button
onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on
the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button
onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off
the light</button>
</body>
</html>
As already noted you can use localStorage to store the src and load it next page load. To use this for your example you could use the following code:-
Html
<button id="btn1">Turn on the light</button>
<img id="myImage" src="off.png">
<button id="btn2">Turn off the light</button>
JS
//set src on page load
if(localStorage.imgSrc) {
document.getElementById('myImage').src = localStorage.imgSrc;
}
//set src and localStorage on click
document.getElementById('btn1').onclick = function() {
localStorage.imgSrc = document.getElementById('myImage').src = 'on.png';
}
document.getElementById('btn2').onclick = function() {
localStorage.imgSrc = document.getElementById('myImage').src = 'off.png';
}
You can use either localstorage that is being supported by the most modern browsers or use cookie.
What i would do is to check in a function if localstorage is being supported if not use cookie like this
function localStorageExists(){
try {
localStorage.setItem(simpleTest, simpleTest);
localStorage.removeItem(simpleTest);
return true;
} catch(e) {
return false;
}
}
function saveOption(value) {
if(localStorageExists() === true){
// available use local storage
localStorage.setItem(option, value);
}else{
// unavailable use cookie
createCookie("option", value, 30);
}
}
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.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
you can also have a function that detects and reads accordingly ;)

Why can't I return cookies in Google Chrome?

I was practicing with the document.cookie attribute and I was able to set and return cookies in my FireFox browswer. However, when I tried to return some cookies in google chrome I didn't return anything. Is there a reason for that? Here is my code in jsfiddle.
HTML
<div id="ex1">
<h2>Example 1</h2>
<p></p>
<h4>results:</h4>
<button id="btn">Return Cookie</button>
<button id="btn2">Set Cookie</button>
</div>
Javascript
function cText(text) {
return document.createTextNode(text);
}
function cElem(elem) {
return document.createElement(elem);
}
function attach(id, text, elem) {
var a = cText(text);
var b = cElem(elem);
b.appendChild(a);
var c = document.getElementById(id).appendChild(b);
return c;
}
document.getElementById('btn').onclick = function() {
var a = document.cookie;
attach('ex1', a, 'p');
}
/* In order to make key = values you have to make a separate line for
each name and value that you are going to put into the document.cookie*/
document.getElementById('btn2').onclick = function() {
document.cookie = "name = Michael Hendricks; expires =" + dayt + ";";
document.cookie = "occupation = Shitty Retail Clerk; expires =" + dayt + ";";
document.cookie = "age = 26 years old with big ol man boobs; expires =" + dayt + ";";
console.log('cookie has been saved');
}
Domain must be null if you set cookies on localhost.
Chrome won't set cookie for 'file://' protocol (as well as safari).
You can use 'Web Server for Chrome' to test your local web app.

Trouble writing cookie value to form field

Being a Javascript novice I am having some trouble implementing Google's Adwords GCLID tracking on our site. I am following their code examples show here https://support.google.com/adwords/answer/2998031.
You can see the cookie being stored but when trying to retrieve it and populate a hidden form field the result is just blank. I have used other variations but that simply results in "Undefined" as the field value.
Here is the code I'm using
Simplified HTML Form
<form class="signup-form" name="signupform" method="post" action="step2.php">
<input type="hidden" name="gclid" id="gclid" value="" />
</form>
Cookie Write Script
<script type="text/javascript">
function setCookie(a,d,b){var c=new Date;c.setTime(c.getTime()+864E5*b);b=";
expires="+c.toGMTString();document.cookie=a+"="+d+b}function getParam(a) {return(a=RegExp("[?&]"+a+"=([^&]*)").exec(window.location.search))&&decodeURIComponent(a[1].replace(/\+/g," "))}var gclid=getParam("gclid");if(gclid){var gclsrc=getParam("gclsrc");(!gclsrc||-1!==gclsrc.indexOf("aw"))&&setCookie("gclid",gclid,90)};
</script>
Cookie Read Script
<script>
function readCookie(name) {
var n = name + "=";
var cookie = document.cookie.split(';');
for(var i=0;i < cookie.length;i++) {
var c = cookie[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(n) == 0){
return c.substring(n.length,c.length);
}
}
return null;
}
function() {
document.getElementById('gclid').value = readCookie('gclid');
}
</script>
function() {
document.getElementById('gclid').value = readCookie('gclid');
}
this is a function without a name that's never called. try replacing it with only
document.getElementById('gclid').value = readCookie('gclid');
I rewrote your write script, I think your cookie is never set.
function setCookie(a,d,b) {
var c = new Date;
c.setTime(c.getTime()+864E5*b);
b="; expires=" + c.toGMTString();
document.cookie = a + "=" + d + b
}
function getParam(a) {
return(a=RegExp("[?&]"+a+"=([^&]*)").exec(window.location.search))&&decodeURIComponent(a[1].replace(/\+/g," "))
}
var gclid=getParam("gclid");
if(gclid) {
var gclsrc = getParam("gclsrc");
if(!gclsrc||-1 !== gclsrc.indexOf("aw")) {
setCookie("gclid", gclid, 90);
alert("Cookie Set!");
}
}
Working script modified from https://support.google.com/adwords/answer/3285060. I just changed the document.onload to window.onload It seems there was too much going on off screen in the DOM.
<script>
window.onload = function getGclid() {
document.getElementById("gclid").value = (name = new
RegExp('(?:^|;\\s*)gclid=([^;]*)').exec(document.cookie)) ?
name.split(",")[1] : ""; }
</script>

unable to display the last visited date

Following is the script that is meant to store the time,date the user last visited a webpage.But nothing happens when i run the HTML with the script.
window.onload = init;
function init() {
var now = new Date();
var last = new Date();
document.cookie = "username=" + ";path=/;expires=" + now.setMonth(now.getMonth() + 2).toGMTString() + ";lastVisit=" + last.toDateString();
var lastVisit = document.cookie.split("=");
document.getElementById("lastVisitedOn").value = lastVisit[6];
}
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="lastVisitTester.js">
</script>
</head>
<body>
<form>
<label>Enter your name <input type="text" id="name_field" /></label> <br/>
<input type="submit" value="submit" />
</form>
<h1 id="lastVisitedOn"></h1>
</body>
</html>
Why is the time/date not getting set for the h tag ? What is wrong with the script ?
window.onload = function () {
var now = new Date(),
expires = now,
lastVisit = document.cookie.match(/lastVisit=([^;]+)/),
userName = 'somebody';
// 1. You should set month in standalone way
expires.setMonth(now.getMonth() + 2);
// 2. For each cookie you set value individually: for username in 1st line, and for lastVisit in 2nd
document.cookie = "username=" + userName + ";path=/;expires=" + expires.toGMTString();
document.cookie = "lastVisit=" + now.toDateString() + ";path=/;expires=" + expires.toGMTString();
// 3. You should test and extract your cookie value BEFORE you set it (see above with cookie match)
// 4. You should test if it's not null also
if (null != lastVisit) {
// 5. You should use innerHTML property for set content
document.getElementById("lastVisitedOn").innerHTML = lastVisit[1];
}
// 6. But in general you should RTFM more :)
// 7. ps: And also use some standard frameworks for this -- not manual raw JS
}
Well there are some problems in your code.
As others has mentioned before:
The function "toGMTString()" is deprecated.
Use "toLocaleString()" or "toUTCString()" instead of "toGMTString()" (see also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date#toGMTString)
You should use innerHTML and you had your index wrong.
You cannot use document.cookie that way. Not sure way.
Example:
var now = new Date();
var last = new Date();
var cookieText = "username=" + ";path=/;expires=" + now.setMonth(now.getMonth() + 2).toLocaleString() + ";lastVisit=" + last.toDateString();
document.cookie = cookieText;
var lastVisit = cookieText .split("=");
document.getElementById("lastVisitedOn").innerHTML = lastVisit[4];

Categories