Home » How to Store Data In Cookies Using JavaScript

How to Store Data In Cookies Using JavaScript

Store Data In Cookies Using JavaScript, before we start setting the cookie using JavaScript, First we should discuss what are Cookies in JS. And then we start all the cookie operations.

How to Store Data In Cookies Using JavaScript

What are Cookies?

Cookies are the set of information that is stored on the user’s system or browser.

Cookies were invented to solve the problem of “how to remember information about the user”,

  • When any user visits any page of the website.
  • Cookies are remember their details by cookie.

JavaScript Cookies Operations

  • Set-Cookie in JS
  • JavaScript Get Cookie by name
  • JavaScript Get all Cookies
  • Delete Cookie JavaScript

Store Data In Cookies using JavaScript (Set Cookie)

For storing user data on cookie using JavaScript is we use document.cookie syntax. Generally we can set 3 parameters to the document.cookie,

  • Any name or other information like “username=John Doe”
  • The expiry time of the cookie from user’s system.
  • Path of the cookies on the same.

Syntax and Example of Set Cookie using JS

Above code is also example of storing cookies in JavaScript.

JavaScript Get Cookie By Name

Generally, developers are struggling with getting the value of the cookie by its name. We will give you a very basic example of JavaScript Get Cookie By Name.

Note: Copy the below code and paste it on the browser’s developer tool console and hit enter to see the output.

On the same code, we use var readallCookie = document.cookie for getting all the cookies.

Example of Get Cookie By Name JavaScript

Output:

JavaScript Get Cookie by name
JavaScript Get Cookie by name

JavaScript Get all Cookies

For getting all the cookies using JavaScript we use the var readallCookie = document.cookie.

Note: Copy the below code and paste it to your console and hit enter to check the complete list of cookies.

Output:

JavaScript Get all Cookies
JavaScript Get all Cookies

Delete Cookie JavaScript

For deletion of cookie in JS you have to follow 2 major steps,

  • Set Cookie value empty.
  • And expiry parameter set to passed date.

Example of Delete Cookie JavaScript

Here username is cookie value and the expires have passed date.

Above are the complete solution for the JavaScript Cookies. If you have any issue with cookies you can comment below we love to help.

Check in-depth https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

Also Check:

Happy Coding..!

Was this article helpful?
YesNo

Advertisement

3 thoughts on “How to Store Data In Cookies Using JavaScript”

  1. Pingback: jQuery Contact Form Send Email Using Ajax - PHPCODER.TECH

  2. Pingback: Complete User Login & Registration System using PHP MySQL With Image Upload | PHPCODER.TECH

  3. Pingback: Count Number of Visits Using PHP Cookies - PHPCODER.TECH

Leave a Reply

Your email address will not be published. Required fields are marked *