How To Work with Javascript Cookie For GET SET and REMOVE

Reading Time: 7 minutes
814 Views

Inside this article we will see the concept i.e How To Work with Javascript Cookie For GET SET and REMOVE. Article contains the classified information i.e Set and Get Data in Cookies with JavaScript.

A cookie in JavaScript is a small data file that websites store on the user’s computer to remember user-specific information such as login credentials, shopping cart contents, preferences, etc. Cookies are accessed and manipulated using the document.cookie property in JavaScript.

Read More: PHP Exception How To Create Your Own Exception Class

Let’s get started.

What is Cookie in Javascript?

A cookie in JavaScript is a small data file that websites store on the user’s computer to remember user-specific information.

Why we use?

Cookies are used for several purposes in web development, including:

  1. Session Management: Cookies can be used to store session IDs, which are used to maintain user sessions across multiple requests. This allows users to remain authenticated and maintain their session data as they navigate the website.
  2. Personalization: Cookies can be used to remember user preferences and settings, such as language preference, theme preference, etc.
  3. Tracking: Cookies can be used to track user behavior and activity on a website, which can be used for analytics and advertising purposes.
  4. E-commerce: Cookies can be used to store information about a user’s shopping cart, such as the items they have added and their quantity, and to remember their shipping and billing information.

Overall, cookies provide a way for websites to remember user-specific information and provide a more personalized and convenient user experience.

How To Work with Cookie in Javascript

To work with cookies in JavaScript, you can use the following methods.

Set Cookie

To set a cookie, you need to assign a value to the document.cookie property. The cookie value should be a string that includes the name of the cookie, its value, and any additional parameters such as expiration date, path, or domain.

Example

// Set a cookie
document.cookie = "username=Sanjay Kumar; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";

In the above code, we are setting a cookie named “username” with the value “Sanjay Kumar“. The cookie will expire on December 18, 2023, at 12:00:00 UTC, and will be accessible on all pages within the domain.

Read More: What is CSRF Token and How To Use in Core PHP Tutorial

Delete Cookie

To delete a cookie, you can set its expiration date to a past time. This will cause the cookie to be immediately removed from the user’s computer.

Example

// Delete a cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

In the above code, we are deleting the “username” cookie by setting its expiration date to January 1, 1970, at 00:00:00 UTC.

Get Cookie

To get the value of a cookie, you can use the document.cookie property to retrieve all cookies associated with the current document. You can then parse this string to find the value of the desired cookie.

// Get a cookie
function getCookie(name) {
    const cookies = document.cookie.split("; ");
    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].split("=");
        if (cookie[0] === name) {
            return cookie[1];
        }
    }
    return null;
}

const username = getCookie("username");
console.log(username);

In the above code, we are defining a function called “getCookie” that takes the name of a cookie as an argument and returns its value.

Read More: How Many Different ways of Writing Functions in JavaScript

The function works by splitting the document.cookie string into an array of cookies, and then iterating over each cookie to find the one with the desired name. If the cookie is found, its value is returned. If not, the function returns null.

Complete Code To Manage Cookie in Javascript

Here’s a complete program in JavaScript that demonstrates how to set, read, and remove cookies:

// Function to set a cookie
function setCookie(name, value, days) {
    let expires = "";
    if (days) {
        let date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

// Function to read a cookie
function getCookie(name) {
    let nameEQ = name + "=";
    let ca = document.cookie.split(';');
    for(let i=0;i < ca.length;i++) {
        let 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 to remove a cookie
function deleteCookie(name) {
    document.cookie = name+'=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
}

// Set a cookie
setCookie("username", "Sanjay Kumar", 7);

// Read a cookie
let username = getCookie("username");
console.log(username);

// Remove a cookie
deleteCookie("username");

We hope this article helped you to learn How To Work with Javascript Cookie For GET SET and REMOVE Tutorial in a very detailed way.

Read More: How To Prevent Website From Being Loaded in Iframe

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.