I started by setting some cookies on my website, the cookie captures the name of the user and displays greetings messages. It was created using guides from w3schools. It worked fine. However, when I try to perform the following String Validation for a test, the cookies magically stop working - no name capture, no greetings messages. The validation also doesn't work and never has. Why? Help? Need some code to make this work:
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 Test(str) {
return /^[a-zA-Z()]+$/.test(str)
}
function Validation() {
document.getElementById("vresult").innerHTML = "";
PetName = prompt("Please enter your favourite pet's name:","");
var T = Test(PetName);
if (T == false) { document.getElementById("vresult").innerHTML = "You did not enter a valid name!"; }
else { document.getElementById("vresult").innerHTML = PetName + " is a lovely name, good choice!!"; }
}
Huh, this is strange but, I've been trying to get this to work for the past two days now and I just went back to my website tab and refreshed and everything worked for the first time. Weird, why is that?
Related
I'm working on a quiz app as part of my college course and have ran into a bit of a roadblock. The code below is for few functions I've wrote. These are supposed to take the user input from the name and email fields, validate the email and store the name as a cookie to be displayed on another page.
I've got this working for the most part, but I'm having trouble getting the stored cookie value to display correctly. It is loading, but is showing as undefined=ryan. If I type a longer name, less and less of the string is displayed. I think there's an issue with the section where I've tried to split the string, but I can't figure it out for the life of me.
Any help or advice would be greatly appreciated.
Thanks :)
function setCookie(cname, cvalue)
{
let userValue = document.getElementById("email").value;
let pos_of_at = userValue.indexOf("#");
if (userValue == " " || pos_of_at<0)
{
alert("You must enter a valid email address");
document.getElementById("email").focus();
}
else
{
cvalue=document.getElementById("userName").value;
document.cookie= cname + " = " + cvalue + ";";
window.location.href="/quiz.html"
}
}
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];
c = c.trim();
if (c.indexOf(c) ==0)
{
return c.substring(name.length, c.length);
}
}
return "cookie not found";
}
function checkCookie()
{
document.getElementById("userName").innerHTML=getCookie("name");
}
Figured it out. Issue was the checkCookie function.
Was
function checkCookie()
{
document.getElementById("userName").innerHTML=getCookie("name");
}
Should have been
function checkCookie()
{
document.getElementById("userName").innerHTML=getCookie();
}
Is it possible to create a session number of page view/visit like PHP, but in JavaScript?
$_SESSION['views'] = 0;
Is it possible to keep track of the number even when user quite the page and get back again?
You could use Cookies. On visit get the cookie and increment it by 1. Or set it to 1 if it doesn't exist
Example:
<p id="yolo"> </p>
<script>
var numberOfVisits = function getCookie('numberOfVisits');
if (numberOfVisits == "")
{
setcookie('numberOfVisits', 1, 100);
}
else
{
numberOfVisits++;
setcookie('numberOfVisits', numberOfVisits, 100);
}
document.getElementById('yolo').innerHTML = getCookie('numberOfVisits');
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(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=/";added
}
</script>
If you only need the data on the client side then use
window.localStorage, it stores data with no expiration date on the client side and it does not send it to the server on every request like cookies, as explained here.
<script>
var varname = "VISIT_COUNTER";
if (localStorage.getItem(varname) === null) {
localStorage.setItem(varname, 1);
} else {
var visits_count = parseInt(localStorage.getItem(varname)) + 1;
localStorage.setItem(varname, visits_count);
console.log("Total visits: " + visits_count);
}
</script>
<script type="text/javascript">
function WorldwideSellingModelCookie(){
days=7;
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'WorldwideSellingModelCookie=Accepted; expires=' + myDate.toGMTString();
}
function CheckCookies(){
var worldwideSellingCookie = getCookie("WorldwideSellingModelCookie");
if (worldwideSellingCookie == "Accepted")
{
jQuery(".alert-worldwide").hide();
}
}
CheckCookies();
</script>
Hi,
The cookie is being created, I am just unsure how to get my if statement to work within my CheckCookies function so that it hide a div on the page?
I am recieving the following console error:
Uncaught ReferenceError: getCookie is not defined
Can anyone advise what I am doing wrong?
Thanks
UPDATE:
<script type="text/javascript">
function WorldwideSellingModelCookie(){
days=7;
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'WorldwideSellingModelCookie=Accepted; expires=' + myDate.toGMTString();
}
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 CheckCookies(){
var worldwideSellingCookie = getCookie("WorldwideSellingModelCookie");
if (worldwideSellingCookie == "Accepted")
{
jQuery(".alert-worldwide").hide();
}
}
CheckCookies();
</script>
Just added the function to check the cookie and seems to be working now, however the div appears for a split second before hiding. Is there any way to stop this from happening?
These are the functions I use to add, get, or clear cookies in JavaScript.
/* function creates cooke with random key */
function setCookie(inputs) {
/* cookie name */
var name = (inputs[0]) ? inputs[0] : "key" + document.cookie.length;
/* cookie expire in 120 seconds */
var date = new Date();
date.setTime(date.getTime() + (120 * 1000));
var expires = "; expires=" + date.toGMTString();
/* sets cookie */
document.cookie = name + "=" + inputs[1] + expires;
};
/* get the cookie based on input */
function getCookie(input) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var name = cookies[i].split('=')[0].toLowerCase();
var value = cookies[i].split('=')[1].toLowerCase();
if (name === input) {
return value;
} else if (value === input) {
return name;
}
}
return "";
};
/* destroy me cookies (well only delete javascript cookies) */
function clearCookies(elements) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf('=');
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
$(elements[0]).val('');
$(elements[1]).val('');
$(elements[2]).val('');
$(elements[3]).html('No Cookie');
};
Also this is a good Document.cookie MDN
I'm building a small HTML game that uses cookies/localStorage to save and load users data. I have an object declared that holds all of the data which is then referenced by the save/load functions and by game calculations:
var iAttack, iDefence, iGold;
// nothing to do with Apple lol...
var data = {
pStats: {
attack: iAttack,
defence: iDefence
},
pInventory: {
gold: iGold
}
}
These will obviously return undefined, but this is before the cookie values are inserted.
So, heres a run-through of whats supposed to happen:
When the window loads, the if statements are gone through to check cookies/localStorage and if there is any previous storage data in the browser. These booleans get assigned to cookies, storageLocal and previousData. This is the code for it:
var previousData = false;
var cookies = false;
var storageLocal = false;
//activated on window.load
function loadData(){
//check for previous data
if (document.cookie != "") {
previousData = true;
console.log("Previous data? " + previousData)
} else if (localStorage.getItem("gold") !== null) {
previousData = true;
console.log("Previous data? " + previousData)
} else {
console.log("Previous data? " + previousData)
}
// check if cookies/localStorage
document.cookie = "foo=bar";
if(document.cookie){
cookies = true;
console.log("Cookies will be used")
} else if (typeof(localStorage) != undefined){
storageLocal = true;
console.log("localStorage will be used")
}
// loadData() continued...
If previousData = false then default values are assigned to the object variables, eg iDefence = 5 and this works fine.
Lets assume that previousData and cookies are true: the function then goes on to inserting the data from the cookies into the object variables like this:
if (previousData) {
if (cookies){
data.pStats.attack = parseInt( readCookie("attack") );
data.pStats.defence = parseInt( readCookie("defence") );
// note that i've used iAttack instead of data.pStats.attack but doesn't work
In the console, if i input iAttack or data.pStats.attack it returns undefined. This is the problem that been keeping me up all of last night trying to work around. Any help would be really appreciated.
This is the saveData function that is triggered by onclick. It inputs the object values into cookies:
function saveData(){
if(cookies){
createCookie("attack", iAttack, 7);
createCookie("defence", iDefence, 7);
//if its the first time saving then the default values of iAttack/def will be used
If you're curious about createCookie() and readCookie(), these are the functions:
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);
}
Let say i've the following function
<script language="javascript">
function myfunction() {
alert("This function was successfully triggered");
}
myfunction(); // trigger it
</script>
I'd like to makes it drop cookie with a name and expiration 24 hours and every-time the user trigger the function myfunction();, it will check for cookies exist and valid or not
What i means is something like this scheme
1) var cookie_name = cowboy; // define name
2) Check of cookie with name cowboy exist and valid of 24 hours since today date.
if exist and valid then do nothing
if not exist or not valid then do the alert and drop cookie with name cookie_name for 24 hours and do the alert alert("This function was successfully triggered");
so any help how to rewrite this function to do so.
You can simply use cookies like this
JavaScript Code:
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);
}
}
}
call the function Inside HTML:
<body onload="checkCookie()">