Using cookies in JavaScript for saving and fetching data

Currently, I am delving into the world of Javascript and attempting to work with cookies. Although my code appears to be correct, there seems to be an issue that I can't quite pinpoint.

function init()
{
    var panel = document.getElementById("panel");

    var user = escape("Dan, 000456");
    var expiry = new Date();
    expiry.setTime(expiry.getTime() + (7*24*60*1000) );
    document.cookie = "myData=" + user + ";" + "expires=" + expiry.toGMTString() + ";";

    if (document.cookie)
    {
        var cookieString = unescape(document.cookie);
        var list = cookieString.split("=");
        if (list[0] === "myData")
        {
            var data = list[1].split(",");
            var userName = data[0];
            var userAcct = data[1];
        }
    }

    panel.innerHTML += "Cookie String:" + cookieString;
    panel.innerHTML += "<br>Split List:" + list;
    panel.innerHTML += "<br>User Name:" + userName;
    panel.innerHTML += "<br>User Account:" + userAcct;
}
document.addEventListener("DOMContentLoaded",init, false);

Upon reviewing the results, they do not match my expectations:

Cookie String:undefined
Split List:undefined
User Name:undefined
User Account:undefined

Answer №1

Now that you've fixed your syntax errors, the main issue lies in the following line:

var user = escape("Dan, 000456");

Note: It appears that the escape function is now deprecated.

To resolve this, update your JavaScript code as follows and ensure that your browser allows cookies:

function init(){

    var panel = document.getElementById("panel");

    var user = ["Dan, 000456"];  //<--change #1
    var expiry = new Date();
    expiry.setTime(expiry.getTime() + (7*24*60*1000) );

    //change #2 below added the array index of user to set the cookie value for myData
    document.cookie = "myData=" + user[0] + ";" + "expires=" + expiry.toGMTString();



    if (document.cookie)
    {
        var cookieString = unescape(document.cookie);
        var list = cookieString.split("=");
        if (list[0] === "myData")
        {
            var data = list[1].split(",");
            var userName = data[0];
            var userAcct = data[1];
        }
    }

    panel.innerHTML += "Cookie String:" + cookieString;
    panel.innerHTML += "<br>Split List:" + list;
    panel.innerHTML += "<br>User Name:" + userName;
    panel.innerHTML += "<br>User Account:" + userAcct;
           }
document.addEventListener("DOMContentLoaded",init, false);

Additionally, ensure that your HTML structure matches the following:

<div id="panel">Test</div>

You can remove the "Test" text from the div in the HTML above if desired. The values assigned to panel.innerHTML should replace it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch up the blogs displayed depending on the category chosen using React

I seem to have hit a roadblock with my current issue. My challenge involves organizing and displaying blog posts according to their categories: const Posts = ({ state }) => { const data = state.source.get(state.router.link); const postsPerCategory ...

Why does the for loop assign the last iteration of jQuery onclick to all elements?

I've encountered an issue with my code that I'd like to discuss var btns = $('.gotobtn'); $('#'+btns.get(0).id).click(function() { document.querySelector('#navigator').pushPage('directions.html', myInf ...

Ignoring TypeScript overloads after the initial overload declaration

Issue An error occurs when attempting to call an overload method for a specific function. The call only works for the first defined overload, causing an error if the call is made to the second overload with mismatched typing compared to the first overload ...

"UIWebView experiences a crash when a long press gesture is performed on a textarea element

Looking to implement a custom keyboard for UIWebView that is entirely based on HTML/JS/CSS for compatibility across multiple devices. To achieve this, I included a notification as shown below: [[NSNotificationCenter defaultCenter] addObserver:self selecto ...

Retrieve information from two observables without the need for separate subscriptions

After my first observable emits user data from Firebase, I need to make a second call to retrieve additional user information from a different collection. While I can handle these operations separately, the second call should only be triggered once the fir ...

Express.js throws an error when trying to access req.session when it

I've searched through multiple posts on this topic, however, none were able to resolve my issue. Below is the code snippet from my server.js file: var express = require('express'); var app = express(); app.configure(function(){ app.set ...

What is the best way to extract the class name from ui.item or event using the function(event, ui)?

Is there a way in jQuery to extract the class name from a function with two parameters, event and ui? For example, consider the following code snippet: $(document).tooltip({ show: null, position: { my: "left top", at: "left bottom ...

Exploring the capabilities of chromaprint.js within a web browser

I'm currently in the process of developing a music streaming platform and I'm looking to include the chromaprint.js library for deduplication purposes. In my workflow, I utilize browserify and gulp. Despite the fact that the library claims it ca ...

Issue with showing an input field following the button click

I'm having a bit of trouble with this function that should add an input element to a div. I've tried using appendChild and also concatenating the object to innerHTML, but no luck so far. Could it be something my beginner's mind is missing? f ...

This JavaScript function is designed to strip HTML elements from a given

"p" tags are disappearing after running the javascript, but they are needed for structuring purposes. Is there a way to retain the html tags in the hidden/secondary text block even after the javascript manipulation? function AddReadMore() { //This lim ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

Activate event in jQuery when clicking on a blank area, away from any div element

I need help figuring out how to hide a div when empty space on the margins of the page is clicked, as opposed to just any area outside of the div. I've managed to achieve this functionality when certain other divs are clicked, but I'm stuck on im ...

Unit tests manipulating JavaScript functions to return undefined values

Currently, I am in the process of testing some JavaScript functions within a larger React application. These functions heavily utilize the module pattern, which leads me to believe that my misunderstanding lies within this pattern. The script I am testing ...

The peculiar characteristics of the dragLeave event in various web browsers

I observed a peculiar behavior while working with drag events in Internet Explorer 11. It seems that adding a 'width' property to the elements triggers the dragLeave event, whereas without it, the event does not fire. Can anyone shed light on why ...

Getting URL Parameters in Angular JS

How should one go about retrieving URL parameters in Angular? For instance, consider this URL: http://example.com/mypage.html?product=1234®ion=4&lang=en Thank you ...

Utilizing Express JS to keep users on the same page upon submitting a form

Although this may seem like a simple query with available tutorials, I am struggling to locate the specific information. I utilized express-generator to create an app and included a basic form in a route. views/form.ejs <div> <h1>This is < ...

Navigate to the previous or next page using JavaScript

I've been struggling to figure out how to navigate one page up and down using simple links, but I haven't found a solution that works for me. The URL I am working with is: . When the "next page" button is clicked, it should go to ?page=2, and whe ...

Combining Angular JS 1 and Laravel 5.2 for seamless integration

Currently, I am in the process of setting up Angular JS 1 with Laravel 5.2 by installing the necessary dependencies using npm. After installation, a node_modules folder was created alongside the app directory. My primary concern is whether it is recommend ...

When zooming out, Leaflet displays both tile layers

I'm currently working on integrating two tile layers along with a control for toggling between them. Below is the code snippet I am using: const layer1: L.TileLayer = L.tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', { ...

`Finding and including the additional object in JavaScript`

Seeking guidance on how to manipulate a specific object in Javascript, I have successfully retrieved the object based on a filter, but I am unsure how to append `'in'='bank' and 'out'='bank'` of non-filtered ids to ...