javascript unable to delete cookie

After conducting extensive research across various articles and links on deleting cookies using JavaScript, I have encountered an issue where the JavaScript code does not seem to be functioning as expected. The code I utilized for setting cookie values using JavaScript is as follows:

var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);

document.cookie="name=" + $scope.user.name;
document.cookie="email=" + $scope.user.email;
document.cookie ="expires=" + now.toGMTString();

Subsequently, in my attempt to remove the cookie, I employed the code provided in the following link from W3 Schools:

document.cookie = "name= ;email= ;expires=Thu, 01 Jan 1970 00:00:00 GMT";

Despite multiple attempts, the cookie persists and does not get deleted. I also tried an alternative method of setting the cookie value in the following manner:

document.cookie="name=" + $scope.user.name+";email=" + $scope.user.email+";expires=" + now.toGMTString();

Even after utilizing this method, the cookie remained undeleted. The discrepancy between the two approaches to assigning cookie values is evident, yet the issue of deletion persists. I have tested these codes on both Chromium

Version 50.0.2661.102 Ubuntu 16.04 (64-bit)

and Opera

Version: 37.0.2178.32

and in both instances, the cookie has not been successfully deleted. Additionally, it is worth noting that these two codes are being implemented within separate API calls.

Answer №1

There appears to be a problem that I can't seem to identify. However, when I add 'path=/', the cookie is successfully created and deleted without any issues. Below is the code for creating and deleting the cookie:

document.cookie="name="+$scope.user.name+";expires="+now.toGMTString()+";path=/";

document.cookie = "name=; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";

Thank you for your assistance.

Answer №2

Whenever you assign a document.cookie, a new cookie is created separately. For instance, when you execute

document.cookie="name=" + $scope.user.name;
, only the name is set without specifying an expires parameter. Similarly,
document.cookie ="expires=" + now.toGMTString();
creates a cookie named expires instead of setting an expiration time.

By using

document.cookie = "name= ;email= ;expires=Thu, 01 Jan 1970 00:00:00 GMT";
, the name cookie should expire, while the email cookie remains since email= is not a valid parameter for cookie setting.

For correct cookie usage, refer to https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie. The valid parameters for setting a cookie are:

;path=path (e.g., '/', '/mydir') Defaults to the current document's location path if not specified.

;domain=domain (e.g., 'example.com' or 'subdomain.example.com'). Defaults to the host part of the current document's location (excluding subdomains) if not specified.

;max-age=max-age-in-seconds (e.g., 60*60*24*365 or 31536e3 for one year)

;expires=date-in-GMTString-format
Defaults to the end of the session if not specified.

;secure (cookie transmitted only over a secure protocol like HTTPS)

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

Execute various settimeout or display functions on various elements of a webpage

Just a heads up, I'm not really experienced in development. More on the newbie side of things, but eager to learn. I've been looking for an answer to my question, but so far haven't come across anything that fits my specific situation. It m ...

What is the best way to incorporate Form Projection into Angular?

I have been attempting to incorporate form projection in Angular, inspired by Kara Erickson's presentation at Angular Connect in 2017, but I am encountering difficulties and errors along the way. view talk here The code provided in the slides is inco ...

Grunt: Can you explain the concept of recursive templates?

Hey there, I'm new to using Grunt and I've run into a puzzling issue with recursive templates. Let me provide you with a concrete and straightforward example: var path = require('path'); module.exports = function(grunt) { grunt.init ...

The selected value is not displayed in the Material UI select component

My select component is showing the menu items and allowing me to select them, but it's not displaying the selected value. However, its handle function is functioning correctly because when I choose an item, the value in the database gets updated. Bel ...

Incorporate External Web Page Information by Clicking a Button

Apologies if this question has already been asked, but despite my efforts to explore the available resources, I have not found a solution to my issue. I currently have an input field where users can enter their website, keyword, or industry. When they cli ...

Restrict the character count in Vue Material chips

Currently, I am utilizing the Vue Material Chips component to gather string arrays. My goal is to limit the character length of each string within the array to 30 characters. The component offers a md-limit prop which restricts the number of strings in th ...

In Typescript, try/catch blocks do not capture return values

I am currently working on a function that performs database operations, with the implementation contained within a try/catch block. Here is an example: async function update({id, ...changes}): Promise<IUserResult> { try { //insert code here retu ...

Rounding up the cents area using JavaScript

So, imagine this scenario: I'm inputting a dollar amount into a text field using code similar to this: <input type="text" name="qtr-revenue-<?php echo $qtr ?>" id="qtr-revenue-<?php echo $qtr ?>" class=&quo ...

Encountering an internal/modules/cjs/loader.js:892 error when attempting to install the newest version of node.js on Windows 10

After recently updating my node.js to the latest version using chocolatey, I encountered a problem with my command prompt displaying the following error: internal/modules/cjs/loader.js:892 throw err; ^ Error: Cannot find module 'C:\Users&bso ...

Transfer Parameters from the Screen to the Header Component in React Navigation

I am facing an issue where I am unable to pass a function as parameter to the header component in react-navigation v5. In the code snippet provided below in filtersscreen.js, my intention is to pass savefilters to headerRight which is located in navigatio ...

The property 'innerHTML' cannot be assigned to null, as stated in Vue

I am dealing with two components that allow for editing JSON objects. Additionally, I have a button that toggles between these two components. Below is the HTML code snippet: <v-btn @click="switchConfigClicked">Switch config</v-btn> <h4 cla ...

AJAX Post Request Function without Form That Does Not Reset

I am currently struggling with understanding the Ajax POST method. I am attempting to make an API request, and since the response has similar parameters, I decided to create a global function that can be used by other HTML/JS pages. However, I am aware tha ...

Establish initial content for the specified div area

I need help setting page1.html to display by default when the page loads. Can you provide some guidance? Appreciate your assistance in advance. <head>     <title>Test</title>     <meta http-equiv="content-type" content="tex ...

I keep encountering the following error message: " ERROR Error Code: 200 Message: Http failure during parsing for http://localhost:3000/login"

My Angular Login component is responsible for passing form data to the OnSubmit method. The goal is to send form data from the front-end application and authenticate users based on matching usernames and passwords in a MySQL database. ***This login form i ...

When it comes to JavaScript, the evaluation order of arguments and delayed evaluation play a crucial

Assuming function( arg1, arg2 ), is it true that arg1 will always evaluate before arg2 (unlike traditional C)? Is there a way to create a function where arguments are not evaluated immediately, but only on demand? For instance, in if( cond1 || cond2 ), c ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

Vue verifies the readiness of two computed properties

Each time I want to determine when multiple computed values are ready, I create another computed property like isFizzAndBuzzReady. computed: { fizz () { return ['f', 'i', 'z', 'z'] // asynchronous data retriev ...

GraphQL Error (Status Code: 429) - Next.js Development issue

If you're facing a GraphQL Error (Code: 429) while working on a nextjs project, here's a handy solution. Here's what happened: I created a headless CMS using Hygraph and NextJS 13 for a blog project. I also utilized the npm package graphql ...

Arrange the Json array by key value in a different order

I have a contact list that is returning in a lengthy form, organized based on order of entry. I am looking to alphabetically sort the list by displayName which is nested within the main array. Can anyone assist with this challenge using JavaScript? Thank ...

Implement the switch case statement within a node.js application

When it comes to implementing a switch case for registration flow, there are various options available. For instance, you can have the user sign up using their email, phone number, and password; or they can opt for signing in with Google, Facebook, and man ...