JavaScript unable to access cookie on the initial attempt

I have been utilizing JavaScript to set and retrieve cookie values. The code I am using can be found at http://www.w3schools.com/js/js_cookies.asp. Upon page load, I check if the cookie exists or not. Everything is functioning properly except for the issue where it fails to read the cookie when initially setting it and attempting to read it on the next page load. Although the cookie gets set, it only fails to read on the first attempt.

Below is the code snippet I have implemented:

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

//To get the cookie:-
function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}
//to Delete the cookie:-
function cookieDelete(c_name) {
    setCookie(c_name, "delete", -1);
}

On page load, my implementation looks like this:

$(document).ready(function () {

       var aZ = getCookie("menuSave");
       if (aZ) {
           //do Something here 
       }
       else {
           setCookie("menuSave", "mysp", null);

       }


   });

Answer №1

To ensure your cookie is accessible, make sure to include a 'path' parameter. In the example below:

path=/ indicates the cookie is accessible across the entire site.
path=/blog/ would restrict access to the /blog/ directory and its subdirectories only.

Answer №2

Although this may not be the direct solution to your issue, here is an alternative and simpler approach that might resolve it for you. I hope this suggestion proves helpful!

Save Menu

localStorage.setItem("menusave", "vale");

Load Value

localStorage.getItem("menusave");

I'm just trying to offer some assistance!

Answer №3

Given that you've specified the question under asp.net category,

You have the ability to establish cookies in this manner:

HttpCookie newCookie = new HttpCookie("userVisit");
newCookie.Value = DateTime.Now.ToString();
newCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(newCookie);

To retrieve the cookie information, utilize the following code:

if(Request.Cookies["userVisit"] != null)
    Label1.Text = Server.HtmlEncode(Request.Cookies["userVisit"].Value);

For more detailed information, please visit the MSDN Cookies overview

Answer №4

By providing a value of null for the expiration days when setting a cookie, it essentially turns the cookie into a session cookie with a short lifespan.

Instead of:

setCookie("menuSave", "mysp", null);

Consider updating it to specify an actual expiration date like this:

setCookie("menuSave", "mysp", 7);

In addition, if you plan on accessing the cookie from pages other than the one where it was originally set, ensure that you also designate a path value in the cookie settings to enable cross-page retrieval.

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

Express-session fails to clear old sessions

Currently, I am diving into a new project where I am utilizing sessions with the express-session library. Take a look at the snippet of code below where I am configuring the session: const IN_PROD = process.env.MODE==='production' app.use(sessi ...

How to initiate a click event with JavaScript through C# in a WebBrowser control

Can the click function be triggered from a C# application? Below is the code that defines the function: $('#connectbtn').unbind('click').attr('disabled', false); $('#connectbtn').bind('click', ...

Converting Variable Values to Element IDs in JavaScript: A Helpful Guide

Is it possible to declare a value in variable A and then access that value as an id in variable B using the method getElementById()? var A = 10; var B = document.getElementById(A); console.log(B); ...

Distinguish the components of a standard union in TypeScript

I am looking to incorporate the following feature: const foo = <S>(newState: S | ((prevState: S) => S)) => {...} This function should accept either a new state of type S, or a function that generates the new state from the old state. In my i ...

Fetching data from a database for Vue.js using the Summernote editor

I previously inquired about integrating summernote with vue.js and received a helpful response here. It worked seamlessly with v-model binding. However, I encountered an issue when attempting to load data from the database for an edit page. The data was n ...

The AJAX response containing jQuery is failing to produce any visible changes

On Page 1 of my website, there is a form that, upon submission, loads Page 2 using jQuery. This process involves calling a PHP page and displaying the output on Page 1 without actually reloading the entire page. To maintain security, I have set up session ...

Expression validation in AngularJS is a powerful tool for ensuring that

Attempting to implement input validation using an Angular expression because validation data will be sourced from the database. Attempting the following code: controller vm.key="ng-required" vm.value="true" html <input type="text" name="fi ...

The combination of Next.JS and React Objects is not acceptable as a React child

Summary: Encountering the error Error: Objects are not valid as a React child (found: [object Promise]) while making a fetch request in a Typescript project. Interestingly, the same code snippet works without errors in a Javascript project. Recently, I ...

Trouble with VueJS: @change event not triggered when <input> value changes

In my VueJS project, I am working with two separate components: One is a modal and the other is a form. Within the modal component, the user inputs a PIN which is then confirmed. This value is then set to an input tag in the form component to save it. T ...

Run JavaScript code last before page unloads

Two pages are involved in this process. On the first page, there is a form that the user completes and then clicks on the submit button. After that, the code for the first page unloads, and the user is redirected to the second page. Actual Issue A loadin ...

The forEach function selectively bypasses certain objects during the iteration process

I have a task that involves writing a function to process an array of objects containing information and save that data in a JSON file. For instance: let arr = [ { creator: 'Girchi', title: ' ...

I am facing an issue in React Native where components disappear when I update my state. How can I fix this problem?

const DetailedSearchScreen=({ navigation })=> { const mydefauthor='no'; const mydeftitle='data'; var [dataset, setDataset]=useState({data:[{Author:'Deneme', Title:'yapiyorum'}]}); return ( <ScrollVi ...

Help me find a way to refine div elements in the HTML response obtained via AJAX

Currently, I am working on creating a dynamic fields form that includes settings such as Label, Name, Id, Min, Max, and Value. Whenever I click on a button, a JavaScript function is triggered to return the definition of a text-box within two separate div ...

What are some ways to dynamically find and import JavaScript files while the code is running?

Currently, I am developing a node.js-based server that manages various devices. The server informs connected clients about its capabilities by utilizing separate JS files that define objects with inheritance through util.inherits(). The issue I am facing ...

Guide to implementing function callbacks in Nodejs using xml2js

In my Node.js project, I am utilizing xml2js to parse XML documents. Since the XML files I need are stored remotely, I make use of a Node.js http request to fetch the XML data and then perform parsing with xml2js in the following manner: var parser = new ...

vuex: initialize values using asynchronous function

My store setup is as follows: export const store = new Vuex.Store({ state: { someProp: someAsyncFn().then(res => res), ... }, ... }) I'm concerned that someProp might not be waiting for the values to be resolved. Is th ...

ASP - Troubleshooting CDO Email Setup Problem

After moving a legacy ASP application from an old server to a Windows 2012 server with IIS 8.5, I encountered email sending failures with the following error in the IIS logs: 80040220|The__SendUsing__configuration_value_is_invalid The current code snip ...

What is the best method for determining values within JSON data?

In my possession is a JSON file containing user data that looks like this: [ { "id": 0, "username": "Antony", "users": [ { "id& ...

What is the best way to iterate through a JSON file?

Looking at my JSON file: { "stats": { "operators": { "recruit1": { "won": 100, "lost": 50, "timePlayed": 1000 }, "recruit2": { "won": 200, ...

Accessing a cookie from a different website

One of my clients is currently managing two separate websites. The first website is a portal site The second website is a booking site The booking site is accessed from the portal and redirects back to the portal after bookings are made. However, the b ...