Reading Cookie that was saved using javascript into html - javascript

I been trying to display Cookies that are saved using javascript into html page
I keep my Javascript in external file and I do not plan on putting this on a server this is for educational client purposes only
I store my cookies using this code Javascript file:`
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
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 "";
}
function checkCookie() {
var user=getCookie("username");
var pass=getCookie("password");
if (user != "" || pass != "") {
alert("Welcome again " + user + " your password is: " + pass);
} else {
user = prompt("Welcome to my Site! Enter your name to begin! :","");
pass = prompt("Make sure to include a password might be useful later! :","");
if ((user != "" && user != null)&&(pass != "" && pass != null)) {
setCookie("username", user, 30);
setCookie("password", pass, 30);
}
}
}
`
and HTML:
<body onload="checkCookie()">
From what I gathered this seems to be working fine since the pop up dialogue says so however
what I want to do is to take this cookie that was saved with alert box and have it displayed on html side so it looks like this
<p>Your cookie is ("Displays the cookie here")</p>
What I tried to do so far is:
<script type="text/javascript">
document.write(getCookie("username"));
</script>
if someone could point me in right directions or say what I'm doing wrong I would be grateful

Add the HTML element of <div id='cookieInfo'></div>
Change your Javascript to:
document.getElementById('cookieInfo').innerHTML = getCookie('userrname');

try this fiddle
this is javascript
$('document').ready(function(){
checkCookie();
document.getElementById("myc").innerHTML = getCookie("username");
})
this is your html
<p>Your name is <span id="myc"></span></p>

Related

Storing Spaces and Colons in Cookie JavaScript

I am making a webpage with a form that saves the data you type in cookies in case you accidentally close the tab or navigate away before submitting.
I would like to know if there is a way to allow whitespace and colons to be in my cookie's data? For instance if user types "test test", on refresh the cookie will be stored and displayed as "test%2520test". Similarly colons display as "%3A". I believe this is possible with using encodeURIComponent but I am not sure exactly how. Below I will include my saveVideo, setCookie, and readCookie JS functions as well as an example input field.
Also, bonus question: What would be the best way to delete each cookie's data upon submit of the form?
<input id="video" name="video" type="text" onchange="saveVideo(this.value);"/>
function saveVideo(cookieValue)
{
var sel = document.getElementById('video');
saveclass = saveclass ? saveclass : document.body.className;
document.body.className = saveclass + ' ' + sel.value;
setCookie('video', cookieValue, 1 );
}
function setCookie(cookieName, cookieValue, nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0)
nDays=1;
expire.setTime(today.getTime() + 60 * 60 * 1000);
document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}
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;
}
</script>
Any tips, pointers, general help is much appreciated!
Just change your code to following in the readCookie function, using decodeURIComponent:
return decodeURIComponent(c.substring(nameEQ.length, c.length));

Why isn't my cookie storing?

I'm trying to set a cookie on a click event to see if a user has actually clicked the respective button. The button is as follows:
Click here
My js to set the cookie is:
function setCookie(cname, cvalue, exdays){
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires =" + d.toGMTString();
document.cookie = cname +"="+ cvalue + ";" + expires;
}
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 "";
}
Then, I set the cookie on a click event:
$("#modalBTN").click(function(){
var clicked = "clicked";
setCookie("clicked", clicked, 30);
console.log(clicked);
});
My click event works. when I console.log(clicked) I see the cookie value, but when I refresh the page the cookie is no longer there.
I check it by:
if(getCookie("clicked") != ""){
//do something else
}
UPDATE
when I call getCookie("otherCookie") it works. But when I call getCookie("clicked") i get returned null. Am I only allowed to have one at a time?
Try this : https://stackoverflow.com/a/24103596/5445351
You can only use console to test the two functions : createCookie & readCookie
Do :
createCookie('ppkcookie','testcookie',7);
Open another page, check if it's still there :
var x = readCookie('ppkcookie')
if (x) {
console.log("ok");
}
Look if it's not your browser that delete cookies automatically.
I tried with Chrome and IE9.

JavaScript cookie stores name but not colour

I have three functions, copied mostly from the W3schools tutorial. checkCookie, getCookie and setCookie.
The code works normally, when I only want to store the user's name but when I try to use the getCookie function to get the person's favourite colour, things go wrong. The program is meant for only storing the user's name: http://jsfiddle.net/rwowf5j8/25/ < working example. For TL;DR go to the bottom because the problem may be simple enough not to need to read the code.
Code from fiddle:
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var title = cname + "=";
var cookie_array = document.cookie.split(';');
for(var i=0; i<cookie_array.length; i++) {
var check = cookie_array[i];
while (check.charAt(0)==' ') check = check.substring(1);
if (check.indexOf(title) != -1) {
return check.substring(title.length, check.length);
}
}
return "";
}
function checkCookie() {
var name=getCookie("name");
if (name != "") {
alert("Welcome again " + name);
} else {
name = prompt("Please enter your name:","");
if (name != null && name != "") {
setCookie("name", name, 30);
}
}
}
function RemoveC() {
document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
function Customise() {
var elem = document.getElementById("Test");
var name=getCookie("name");
if (name != "") {
elem.innerHTML = "Hi there, " + name;
} else {
elem.innerHTML = "";
}
}
</script>
<body onload="checkCookie(); Customise()">
<button onclick="RemoveC()">Remove Cookie</button>
<p id="Test">
</p>
</body>
I tried to amend the code to also store the users favourite colour. I changed the setCookie and checkCookie functions to the following:
function setCookie(cname, ccolour, cvalue, cvalue2, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+ccolour+"="+cvalue2+"; "expires;
}
function checkCookie() {
var name=getCookie("name");
if (name != "") {
alert("Welcome again " + name);
} else {
name = prompt("Please enter your name:","");
var colorC = prompt("Please enter your favourite colour:","");
if (name != null && name != "" && colorC != "" && colorC != null) {
setCookie("name", "colour", name, colorC, 30);
}
}
}
I realise that there is a problem wit the beginning of the checkCookie function as in it only checks if the name is there and doesnt check that colour is there but I'm just testing at the moment.
I also changed the Customise function to get the colour and alert it to the user
var Fcolour = getCookie("colour");
alert(Fcolour);
Here is the fiddle for the new code that doesn't store colour properly: http://jsfiddle.net/rwowf5j8/28/
Now, nothing works. The checkCookie function doesn't run completely. I suspect there is a problem with me semicolons. I don't understand cookies very well. Can you store multiple values divided my ";"? like, name=test; colour=test; something=test; expdate.....

Cookies in HTML page

So this code that i have works perfectly and exactly as i want it to. What is does is it takes the input "textmoney" and calculates how much money you make yearly. I have a link to another calculator that makes a more percise prediction. Basically i want to know how to have the website remember what the data input was on "textmoney" on the first page, so that when the user clicks on the more advanced calculator the website will remember the value of "textmoney" and the user won't have to type in the same data again. Do i use cookies?
Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
var $demo = $('#demo');
var $textMoney = $('#textmoney');
var $moneydiv = $('#moneydiv');
$('#advanced').hide();
function getmoney(){
var money = $textMoney.val();
if (isNaN(money) || money === '') {
$demo.text('You aint enter no $$$$$$');
} else {
var dailyE = $textMoney.val() * 365;
$demo.text('$' + dailyE + ' per day');
}
}
// on enter key
$textMoney.keydown(function(e) {
if (e.which === 13) {
getmoney();
$('#advanced').show();
} else if ($(this).val() === '') {
$demo.text('');
$('#advanced').hide();
}
}).mouseover(function() {
$(this).css('border', '1px solid black');
}).mouseout(function() {
$(this).css('border', '1px solid grey');
});
// on click
$moneydiv.click(function(){
getmoney();
$('#advanced').show();
});
});
</script>
You may use HTML5 Web Storate:
// Store
localStorage.setItem("textmoney", $textMoney.val());
// Retrieve
$textMoney.val(localStorage.getItem("textmoney"));
From W3Schools:
The data in localStorage will not be deleted when the browser is closed, and will be available the next day, week, or year.
If you want to store the value just while the browser (or tab) is open. You can use sessionStorage instead:
// Store
sessionStorage.setItem("textmoney", $textMoney.val());
// Retrieve
$textMoney.val(sessionStorage.getItem("textmoney"));
If your browser desn't support HTML5, cookies are also good idea but be aware that some browsers can also have blocked cookies.
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;
}
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 "";
}
// Store
setCookie("textmoney", $textMoney.val(), 999999 /* Expiration*/);
// Retrieve
$textMoney.val(getCookie("textmoney"));

initialization and deletion of Cookies

I'm new to javascript and stuck with the following problem with cookies
Problem
The cookie value in the following problem is a name.
I'm trying to display the user's name from the cookie. When the page is opened, if there is a cookie value, then the cookie value must be displayed with appropriate greeting. But if there is no cookie value when the page is opened, a prompt box must pop up asking the name of the user. If the name(cookie value) of the user is displayed wrongly on the page, for instance John opens the page and the name displayed is Paul, then he must click on "click here if You are not Paul" and the cookie must be deleted and John must see a prompt box asking for his name. Then the new cookie value must be whatever John enters in the prompt box
Code
The greetings part is working perfectly. I have the following code.FYI, I'm testing this on a website, not local machine.
<script>
var now = new Date();
var hours = now.getHours();
var name, greeting, count,a;
if(hours < 12)
{
greeting = "Good Morning";
}
else
{
if(hours < 18)
{
greeting = "Good Afternoon";
}
else
{
greeting = "Good Evening";
}
}
if(document.cookie)
{
var newCookie = document.cookie;
var cookieVals = newCookie.split("=");
name = cookieVals[1];
}
else
{
name = window.prompt("Please enter your name","name");
document.cookie = "name=" + name;
}
a = greeting + " " +name + ", Welcome to Survey Page! </h1>" + "<a href = '#' onClick='return false;' onMouseDown='wrongPerson()'> " +"Click here if you are not " + name + "</a>";
function wrongPerson()
{
document.cookie= "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
location.reload();
}
<p><span id="verify"></span></p>
<script>document.getElementById("verify").innerHTML = a;</script>
Output
I'm getting the following output
Good Evening 74bec77-148138c40e3-42e9b6fa-5; _ga, Welcome to Survey Page! Click here if you are not 74bec77-148138c40e3-42e9b6fa-5; _ga
Nothing happens when I reload the page or when I click on the link "Click here if you are not 74bec77-148138c40e3-42e9b6fa-5; _ga".
Can someone enlighten me on this?
Your javascript :
if(document.cookie)
{
var newCookie = document.cookie;
var cookieVals = newCookie.split("=");
name = cookieVals[1];
}
checks that is there anything in the cookie and if it is then it will not ask for new name. When the user clicks on I am not ... then The function wrongPerson() sets the cookie to "name=........" which when compare at starting by your if will always return true because
In javascript non zero values are TRUE
So it will think that a user is present. If you will make the function wrongPerson() make the cookie 0 or "" , then the if will get FALSE and the statement (used to ask for name) will get executed.
Fixed Function:
function wrongPerson()
{
document.cookie= "";
location.reload();
}
Create / Call functions it is much easier to understand. source
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
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) != -1) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>

Categories