What could be the reason behind the failure of $cookieStore.get() in retrieving the value?

I am currently testing the cookie functionality in AngularJS. I'm encountering an issue where the console is returning 'undefined' when trying to retrieve a saved value from the cookie using $cookieStore.put(). It seems to work fine when setting or saving the value, but retrieving it returns undefined.

<!DOCTYPE html>
<head  runat="server">
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-cookies.js"></script>
    <script>
        angular.module('app', ['ngCookies']).controller('MyController', ['$scope','$cookieStore', function($scope, $cookieStore) {

            $scope.WriteCookie = function() {           
                $cookieStore.put('visited', $scope.yes);                
                console.log($cookieStore.get('visited'));
            }       

            $scope.ReadCookie = function() {
                $cookieStore.get('visited');
                console.log($cookieStore.get('visited'));
            }

        }]);
    </script>
</head>
<body ng-app="app">
    <form>
    <div ng-controller="MyController">      
    <input type="button" value="Write Cookie" ng-click="WriteCookie()" />
    <input type="text" ng-model="yes" />

    <input type="button" value="Read Cookie" ng-click="ReadCookie()" />
    <input type="text" ng-model="cookie" />
    </div>
    </form>
</body>
</html>

Answer ā„–1

Here is a helpful tip:

Upgrade to cookie version 1.6.6 and switch to using $cookies instead of $cookieStore

angular.module('myApp', ['ngCookies'])
.controller('myController', ['$cookies', function($cookies) {

  $cookies.put('myFavorite', 'chocolate chip');
  var favoriteCookie = $cookies.get('myFavorite');

  console.log('favoriteCookie', favoriteCookie);

}]);

Answer ā„–2

After conducting two different tests on your code, I discovered some interesting results. When opening the file directly, the cookie returned as 'undefined', but when accessing it through a server, the cookie appeared as expected. Upon further investigation, I found that certain browsers, such as Chrome, restrict setting cookies for files opened locally. Learn more about this issue here.

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

"Converting a database table record into a JavaScript array: Step-by-step guide

I'm currently expanding my knowledge of PHP by working on a small project. Within my database, I have a table called city_name which consists of columns for id, name, longitude, and latitude. Typically, this table contains around 10-15 rows. When a us ...

Verifying the existence of a user in my mongodb database before adding a new user to avoid multiple registrations with the same email address

Attempted to use Express, I am in the process of creating a .js file that manages POST requests and checks whether a user already exists before adding them to my MongoDB database. I set up two separate MongoClient connections for different scenarios: one t ...

Is there a way to display all of them inline in Woocommerce?

Can anyone assist with making each of these inline? https://i.sstatic.net/YF9bu.png <div class="atc_nsv"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <ul> <li><img class="ad lazyloaded" data-src="//cdn.shopif ...

Skipping code in JavaScript/jQuery function on window load

I have created a function that applies specific CSS rules to elements when the window is fully loaded. Check out my code below: function applyHover() { $('.view_preloader .overlay').css('opacity',1); $('.view_pre ...

React date format error: RangeError - Time value is invalid

I'm utilizing a date in my React app using the following code: const messageDate = new Date(Date.parse(createdDate)) const options = { month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' } as const ...

Adjust font size using jQuery to its maximum and minimum limits

My jQuery script enables me to adjust the font-size and line-height of my website's CSS. However, I want to restrict the increase size to three clicks and allow the decrease size only after the increase size link has been clicked - ensuring that the d ...

Tips for creating a column with add, edit, and delete buttons in PHP

I found this code on a website that handles pagination and search functionality. However, I am looking to enhance it by adding an icon or button in a column that will allow users to link to the edit and delete functions for specific data selected in the ta ...

Doubt surrounding the behavior of Node.js when a file is required that does not export anything from a module

My understanding of Node.js' require() function and module.exports is high-level, but I still find some behaviors confusing. Imagine I have two simple one-line files named a.js and b.js. In a.js: require('./b.js'); and in b.js: console. ...

Switch the URL of the current tab to a different one by clicking a button within a Chrome extension with the help of JavaScript

Could someone assist me in changing the current tab URL to a different website, such as , using a chrome extension? Here is my JavaScript code: chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { var tab = tabs[0]; console.log(tab.url) ...

The image fails to display when using THREE.js and Panolens.js

Trying to create a 360-degree environment with informational buttons using THREE.js and Panolens.JS However, I'm unable to resolve why the image is not appearing. Continuously encountering the error: Uncaught ReferenceError: process is not defined. ...

Prevent double-click selection functionality

In my code, I have a CSS class called .noselect that disables text selection using various browser-specific properties. However, I am now looking to modify it so that the text can still be selected, but not when the user double-clicks on it. Is there a wa ...

Group an object by its name using Java Script/Vue.Js

I am looking to group objects by partial name and assign them to variables data = { SCHOOL-ADMISSION_YEAR: "2021" SCHOOL-SCHOOL_NAME: "ABC SCHOOL" SCHOOL-SCHOOL_LOCATION: "NEWYORK" ENROLLMENT-ADMISSION_YEAR: " ...

Streamline the testing process to ensure compatibility with jQuery version 2.x

I currently have a substantial JavaScript code base that is all built on jQuery 1.8. I am planning to upgrade to jQuery 2.1 in the near future and I am fully aware that many parts of my code will likely break during this process. Is there any efficient me ...

Is there a way to apply a setTimeout to a <div> element upon the first click, but not on subsequent clicks?

Check out the fiddle I've created: http://jsfiddle.net/dkarasinski/dj2nqy9c/1/ This is the basic code. I need assistance with a functionality where clicking on a black box opens a black background and then after 500ms a red box appears. I want the ...

Grabbing nested JSON Array data using Node.js

As a beginner in Node.js, Iā€™m attempting to extract data from the JSON below: var data1 = { "_id":"R1::table::A1::order::167::comanda::2", "_rev":"1-ed6df32d3b4df9cc8019e38d655a86f5", "comanda":[ [ { ...

Error message encountered in AngularJS when trying to send Fullcalendar: TypeError - Cannot access property '__id' of an undefined object

Recently, I integrated angular-ui-calendar into my website. Within the controller, I implemented the following: define(['underscore'], function (_) { "use strict"; var SearchController = function ($scope, $location, OrdersService, U ...

Implementing Angular CDK for a dynamic drag-and-drop list featuring both parent and child elements

I'm currently working on setting up a drag and drop list within Angular using the Angular CDK library. My goal is to create a list that includes both parent and child elements, with the ability to drag and drop both parent items as well as their respe ...

Using NodeJS to extract information from Opendata JSON files

I'm currently working on a project that involves fetching JSON data from an Open Dataset using NodeJS and passing it to angular. The challenge I'm facing is that I'm receiving a JSON file instead of a JSON object, which makes it difficult to ...

"Modifying state within a child component and utilizing the refreshed value in the parent component

I'm currently working on creating a simple header mini cart with a cart item counter in NextJS. I'm utilizing the form state value in the header component and then passing that value to the child components of the header where the numerical quant ...

AngularJS - "Select All" elements that are currently within the view

Currently, I am faced with the challenge of selecting only the visible items in a list. The list is long and has paging applied to it, meaning only a few items are displayed at once. I have implemented a "Select All" button that should only select the curr ...