A cookie is a Temporary Web Storage File, which stores the keywords searched by the user on the Internet or filled information up to the time period set by the server. It is known by many names, such as Web Cookie, Browser Cookie, and HTTP Cookie.
In this article, we’ll discuss JavaScript get cookie by name and Set cookie and get a cookie with JavaScript.
I’m working on website design in which I’m trying to set a cookie depending on which I will add reference of Javascript file in my HTML Page.
I have an HTML page with a list of HTML control options, and different Javascript files as values. So for completing this task I have written javascript code for Set, Delete, and Read cookie value by name in JavaScript.Let’s have a look
A cookie is mainly of 2 Type,
Session Cookie: Cookie that automatically deletes as soon as the browser is closed is called Session Cookie. Its use is mostly for government websites or if you build a highly secure website.
Permanent Cookie: cookie that presents in the browser even after closing Browser, the information you have searched or filled on the Internet, is stored for 1 Day, 1 Month, or 1 year. All such cookie is called Permanent Cookie. This type of cookie is used for Travel or Online Booking Website.
How do cookies work?
When any website is created, cookies are made by Web Developers. As soon as you open such a website. It lets you drop your cookies file on your Computer Browser.
After cookies are set on your browser, it works like Cache Memory and whatever you search on the Internet. Cookies keep storing that information and send it to their website server.
In this Part I will explain you Following Points:-
- How to Deal with Cookies in JavaScript
- Set cookie and get cookie with JavaScript
- How to set cookie’s expire date with JavaScript?
- Setting cookie to expire after x day
Html Code
<!DOCTYPE html>
<html>
<head>
<title>DotNetPeTips</title>
<meta charset="utf-8" />
</head>
<body>
<fieldset>
<legend>Create Cookie</legend>
<button type="button" onclick="CreateCookie('testcookie',10,'testing cookie message')">Create Cookie</button>
<button type="button" onclick="getCookie('testcookie')">Read Cookie</button>
<button type="button" onclick="DeleteCookie('testcookie')">Delete Cookie</button>
</fieldset>
<script type="text/javascript">
function SetCookie(cookie_name, days,value) {
debugger;
var today = new Date();
var expiresdate = new Date(today.setTime(today.getTime() + days * 86400000));
document.cookie = cookie_name + "=" + value + "; expires=" +
expiresdate.toGMTString();
alert("cookie set successfully!");
}
function getCookie(cookie_name) {
if (document.cookie.length > 0) {
cookie_start = document.cookie.indexOf(cookie_name);
if (cookie_start) {
cookie_start = cookie_start + cookie_name.length + 1;
cookie_end = document.cookie.indexOf(";", cookie_start);
if (cookie_end == -1) {
cookie_end = document.cookie.length;
}
alert(unescape(document.cookie.substring(cookie_start, cookie_end)));
return unescape(document.cookie.substring(cookie_start, cookie_end));
}
}
return "";
}
function DeleteCookie(cookie_name) {
debugger
SetCookie(cookie_name, '', -2)
}
</script>
</body>
</html>
Create Cookie:-
- Expires − The date when you the cookie will expire. If you set this value blank, then the cookie will expire when the user closes the browser. These cookies also are known as Session Cookie or temporary cookies.
- Domain −Url of your Web Application.
- Path − The path web page that sets the cookie. you can set value blank if you want to read the cookie from any page.
- Secure − if you set this field “secure”, then the cookie only be retrieved with a secure server like only with https.
- Name and Value − Cookies are store in the form of key-value pairs. using this property can define the name of the cookie which will help you when reading the cookie value.
function SetCookie(cookie_name, days,value) {
debugger;
var today = new Date();
var expiresdate = new Date(today.setTime(today.getTime() + days * 86400000));
document.cookie = cookie_name + "=" + value + "; expires=" +
expiresdate.toGMTString();
alert("cookie set successfully!");
}
Read Cookie:-
Reading a cookie value very simple,the value of the document.cookie object is the cookie.
function getCookie(cookie_name) {
if (document.cookie.length > 0) {
cookie_start = document.cookie.indexOf(cookie_name);
if (cookie_start) {
cookie_start = cookie_start + cookie_name.length + 1;
cookie_end = document.cookie.indexOf(";", cookie_start);
if (cookie_end == -1) {
cookie_end = document.cookie.length;
}
alert(unescape(document.cookie.substring(cookie_start, cookie_end)));
return unescape(document.cookie.substring(cookie_start, cookie_end));
}
}
return "";
}
Delete Cookie:-
If you want to delete a cookie then you just need to set the expiry date to a time in the past.
function DeleteCookie(cookie_name) {
debugger
SetCookie(cookie_name, '', -2)
}
Whenever you use any browser, some information gets from our phone or our computer in the form of a file, as which keyword you have used and which website you have opened, then all such information is saved in a file and kept in our mobile computer data. given so that it can be used later.
Like we told you that whenever we search on the browser, then their small files are saved in our computer or our phone. With this, a message is sent to the website server whenever we open a site or do some search, all its data is saved in a file. When you go to the site, you are shown many such things that you have searched before or that you are interested in. This happens because a file of cookies is saved in our mobile or our computer, and then all the advertisements are shown on the Internet accordingly.
Cookies can be used easily and can also be implemented.
It takes very little data to save the file on the server, which is a big advantage of it.
When our browser is closed for some reason, then using this we can open our opened tab again. It help a lot to save time and save data.
Cookies depend on all browsers, such as if you use Chrome browser, then you will not be able to use their cookies in other browsers like Internet Explorer, Firefox. Also depend on the domain because the data taken from one domain will not be able to tell about the other domain.Cookies file is about 4KB, which can be of different size in different browsers.
The post [Solved]-Set,Delete and Read cookie value by name in JavaScript appeared first on Software Development | Programming Tutorials.
Read More Articles
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- jQuery Ajax GET Example with Parameters
- How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- How to add, edit and delete rows of an HTML table with Jquery?
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- [Solved]-How to Upload pdf file using jquery MVC?
- Dynamically creating graphs with jQuery
- @Html.validate method, how does it work?
- File upload multi-select
- jQuery-Mobile Disable Page Dragging & prevent Scroll over Header/Footer
- jQuery Sortable elements not always staying inside parent
- jQuery plugin overrides keypress events
- Button hover will change the background of div and a picture in between two blocks
- jQuery if/else hasClass (else not working)
- JQuery Validation Help
- Event delegation gives null value
- How to split html tags in jquery?
- Count Divs and Hide some
- td cuts when page break to next page
- Initialize onchange event inside a loop - Javascript
- single or double quote in javascript append
- stop audio from playing when another audio starts
- Loading a few files from Javascript
- Is there a way to dynamically add buttons to a JSON table?
- How to avoid multiple occurrences on an object?
- Javascript on a new page load to move an anchor below a top fixed element
- jQuery .CSS opacity not working
- JQuery Date Picker Dynamic altField
- Alternative to css3 not selector
- Address Validator using Google Maps
- jQuery fadeIn/Out stuttering with rounded div
- Masonry.js column numbers change on browser width
- Bootstrap loading icon not shown when clicking on button
- Website Structure Has Lost Browser Back Capability
- need some help with jquery tabs plugin
- Sorting date column by DD/MM/YYY in jQuery DataTables 1.10.2
- How to not use canvas clearRect() for multiple drawings?
- Restrict Ajax Mechanism while enter key is pressed in jsf component
- Calls to update DOM are ignored in Phonegap app with iPhone 3G running iOS 3.0
- Jquery + add checkbox values to href element
- Dialogflow messenger height customization issue on Firefox browser
- iFrame postMessage Once Modal Loads
- replace the anchor tag with a span or div or p
- Get a legitimate array from ajax & jquery call
- Append an input after a textarea with Javascript or jQuery
- Usefulness of extending jQuery core
- Way to lock a select element after a radio button is selected in jQuery
- xCode 7 update broke Cordova jQuery $.ajax() calls
- How to show div, based on Html.DropDownList?
- Scaling Down Bootstrap
- How to AJAX POST to a PHP script for address validation with SmartyStreets?
- jQuery Validation - Changing "Required" Attribute based on other fields
- Parallax effect with GSAP
- jQuery Selector only on first level not working?
- Icon Disappears After Drop-down is Selected (and label value loaded dynamically)
- JQuery and Submit button
- javascript function with $.get won't return value
- jQuery "Uncaught" on ajax call inside try... catch
- Session variable not updating after AJAX call
- how can i change nivo slider parameters while it's running?
- How do I add an animation to another element when another div class is hovered?
- Issues calling a method after making an ajax call
- How to hook into a jQuery widget's function?
- Using javascript:function syntax versus jQuery selector to make Ajax calls
- Simple regex to extract contents between square brackets in jQuery
- Find child H3 and check if has value
- How to Implement linq on dictionary in C#?
- How to Invoke JS function in IFrame from code behind
- how to find the element is resized using jQuery
- CORS preflight not returning
- Multiple hidden divs to be shown
- Is it possible to target a specific tablesorter column by class when using the filter widget?
- WebGL Earth restart animation at current location
- Set current day active on datepickers with Jquery
- Range slider, left value always less than right value
- GET document canceled upon first visit (Chrome)
- Get number of remaining files in Plupload queue
- ASP.NET ajax c# always returns undefined
- How to access object value
- What is wrong with this recursive Promise function with jQuery Deferred
- Failed to load resource: the server responded with a status 404(not found)
- In jQuery how to wait for specific value on variable
- Can only drag and drop rows that are on the unlocked side of kendo ui grid
- how to prevent doubling the input file if the user opened it and closed it without choosing a file
- Prev Next Button Responsive
- Multiple Google Maps won't work with Bootstrap 3 Tabs
- jQuery gentle scroll
- detect which word has been clicked inside link
- jQuery .ajax: How to handle Custom Validation Error Message, REST API, 400 status code?
- Getting back to the original selector in chain?
- How to set value in dynamically added rows form using jquery?
- Possible scope issue with jQuery plugin?
- Change position of other photos by SlideDown & SlideUp in JQuery
- Is there any way to forcibly abort a JavaScript (or jQuery) function which is being executed?
- Add jquery to rails, "slider is not a function"
- JQuery UI - Add dblclick Event to Modal dialogs
- Drilldown for grouped column chart in highcharts
- Need a better way to validate ASP.NET checkboxes using a jquery validation plugin?
- display child div on focus using jquery
- Error: javascript key in invalid format integer
- PouchDB transaction error
- How to free draw ellipse using Fabricjs?
- Google recaptcha validation with Jquery
- How to append a span tag inside another span tag in jquery?
- jqgrid password field not only in edit mode
- Cannot read property 'substring' of undefined after putting the line in setTimeout
- jQuery Tooltip Showing Tabs But Not Newlines?
- Function not defined when running .mb_YTPlayer();
- Javascript - ZeroClipboard copied content doesn't get updated
- Getting a specific number of JSON items with jQuery from tumblr feed
- Modal pop up repeating data
- slow .toggleSLide() on iPad 3
- Want to keep background fixed until a certain scrolldown point
- I can't set the time when creating a 'modal box'
- How to notify view from model to change a value in backbone
- ajax calling C# method
- Symfony form - reorder / sort CollectionType elements
- How to capture barcode hex code keystrokes in an input tag
- jQuery changes class - div disappears in Firefox, fine in Chrome, IE, Safari
- Select2 with Knockout.js inital value
- Find current element of slider
- Monitor Twitter for multiple words / hashtags?
- Best way to access jQuery version of DOM element from inside click event?
- $ionicScrollDelegate.scrollTop() doesn't allow me to scroll up manually after it scrolls down my list
- Toggle table - increase rowspan to accommodate extra toggled row
- jqPlot Pie chart data label does not show
- how to convert page to pdf in php
- Find text between two characters and for each, do something
- Show the total of rows and columns in jquery full calendar based on the month
- Slick lightbox use image title as caption
- Pass raw html from view to controller
- Add a class to a "fixed" img in stellar parallax
- how to combine two selectors?
- Error Message: Unable to get value of the property 'replace': object is null or undefined in IE9
- How to call a href by onclick event of a button?
- Datatables Multi Filter Select - each column is treated differently
- How do I flick a DIV and have it move in the right direction?
- Create a new div and move the existing div
- IE9: Form values revert back to old value after AJAX form submit
- Bootstrap modal dialog return message in MVC
- spin child div with text on time
- Adding jQuery slideToggle() to oncliked event on anchor link
- Rails - make link work with ajax
- object is not a function on stripe javascript
- How to serialize multiple select values, which were built into a $ each loop
- How to see which radio buttons are clicked Jquery
- SapUI5 includeScript is not loading js files in fiori launch pad
- Cant Call jQuery in PHP echo
- jQuery redefined by requirejs in legacy app
- Set Value For Dialog Display
- Handling Multiple ids in java script
- contentEditable ExecCommand "bold" fails to fire
- Where to put script tag inside jQuery mobile single page template
- check if value already exists in the JSON added using AJAX
- How can I apply same style from element that changes in HTML to one that doesn't change in HTML?
- Show contents of localStorage into div
- Jquery ajax promise returning undefined