Having some trouble with setting and getting cookies - javascript

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();
}

Related

Variable passed as parameter returning undefined JS

I am trying to pass a variable which stores a cookie name in JS, the correct value is stored when writing the cookie but when passed to the function to read the cookie it returns undefined, returning the cookie value as NULL. It is for a college project, and I am working from the code example on this site here https://www.quirksmode.org/js/cookies.html
function WriteCookie(cname, username) {
//Cookies variables
var cname = 'user';
var username = document.getElementById("username").value;
//check if the user has entered a value and alert if they haven't
if (document.myform.username.value == "") {
alert("Please enter a value in the name field");
document.getElementById("username").focus();
return false
}
//variables for emial validation
var emailtext = document.myform.email.value;
var pos_of_at = emailtext.indexOf('#');
//checking email address for an #
if (pos_of_at <= 0) {
alert("Invalid Email");
document.getElementById("email").focus();
return false;
}
//store the cookie
document.cookie = cname + "=" + username + "; path=/";
location.href = 'welcome.html';
}
//function to read the cookie
function readCookie(cname) {
//variable for loop
var nameEQ = 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, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length)
}
return null;
}
function cookiealert() {
alert(readCookie());
}
It is possible that you're using httponly cookie causing this.
From MDN docs:
A cookie with the HttpOnly attribute is inaccessible to the JavaScript Document.cookie API; it is sent only to the server. For example, cookies that persist server-side sessions don't need to be available to JavaScript, and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks.
Therefore, your for loop does not return any value and the function returns back null.

Can only have one function in JS module

I found this post on how to write a cookie with Blazor (as it turns out, that involves JavaScript). Using the sample from the post, I made my own version, with both a Write and a Read function. So it looks like this:
<script>
window.blazorExtensions = {
WriteCookie: function (name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
};
ReadCookie: function (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 "";
}
}
</script>
Only problem is... It doesn't work :-(
If I only have theWriteCookie method it works. If I only have the ReadCookie method it works. But if I have both, it does not work.
From the looks of it, the window part is a module, but I could be wrong. However, this it what VS Code says, in the tool tip:
Can anyone explain to me, why this does not work? I tried Google, but since I struggle with the terminology, it's hard to find something useful. I am used to C# and thought that the window.blazorExtension was some sort of namespace.
If it's any help, here is how I invoke the functions:
public async Task WriteCookeAsync() {
var test = await JSRuntime.InvokeAsync<object>("blazorExtensions.WriteCookie", "Color", colorCode, 7);
}
Without actually checking your functions' for correctness, I can see the object window.blazorExtensions is not defined correctly. What you need to do is to change the semi-colon after the WriteCookie function definition to a comma as JavaScript object properties are comma-separated...
window.blazorExtensions = {
WriteCookie: function (name, value, days) {
//...
},
ReadCookie: function (cname) {
//...
},
};

dynamically changing url to reset to default view

I have been attempting to write code to dynamically change a particular href value to the current url. It works to a point, but the problem is that on my page I have a few different filters, so when one is clicked, the current url is then overridden.
is there a way to grab the first url as a variable when the page loads and keep it the same until someone leaves the page ?
I've been experimenting with various conditional statements but not had much luck.
The code that works is this one :
$(document).ready(function() {
var currenturl = document.URL;
$("#reset").attr("href", currenturl);
});
Thanks in advance!
You could store the initial url as a cookie.
$(document).ready(function() {
function setCookie(cname, cvalue) {
document.cookie = cname + "=" + cvalue + ";path=/";
}
function getCookie(cname) {
const name = cname + "=";
const ca = document.cookie.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 "";
}
setCookies('INITIAL_URL', document.URL);
$("#reset").attr("href", getCookie('INITIAL_URL'));
});
And then use some logic when you need to reset the cookie value.

Javascript string validation with cookies

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?

Javascript - How to display only the value of a cookie?

I have searched several places trying to find out how to do display only the value of a cookie rather than the whole key but they all seemed needlessly complex for what I'm doing. I've got a single cookie with only one key, userName = something, and I can't figure out how to display only the "something" rather than userName = something.
function userCookie(form)
{
if(form.User_Name.value == "")
{
alert("Cannot accept a blank user name, please enter a valid name");
return false;
}
else
{
document.cookie="userName=" + form.User_Name.value;
alert(document.cookie);
return false;
}
}
function newWindow()
{
var userWindow = window.open("","MyUserName","height=300,width=300");
userWindow.document.open();
userWindow.document.write("<p>Welcome Back</p>");
userWindow.document.write(document.cookie);
userWindow.document.close();
}
If you always have exactly one cookie then document.cookie.split("=")[1] would be simple enough.
document.cookie will always return key,value pair like cookie1=value1;cookie2=value2.
You can use the following function to split the cookieName and "=" from the document.cookie to get the value.
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 "";
}
The code is from w3schools.
var cookieArray = document.cookie.split("; "),
cookieObject = {},
i, pair;
for (i = cookieArray.length - 1; i >= 0; i--) {
pair = cookieArray[i].split("=");
cookieObject[pair[0]] = pair[1];
}
alert(cookieObject.userName);
function getCookie(name) {
let x = document.cookie.split(";").find(a => a.includes(name + "="));
return !!x ? x.trim().substr(name.length+1) : ""
}

Categories