Can Jquery Read/Write Cookies to a Browser

How do I set/unset a cookie with jQuery?

Update April 2019

jQuery isn't needed for cookie reading/manipulation, so don't use the original answer below.

Go to https://github.com/js-cookie/js-cookie instead, and use the library there that doesn't depend on jQuery.

Basic examples:

// Set a cookie
Cookies.set('name', 'value');

// Read the cookie
Cookies.get('name') => // => 'value'

See the docs on github for details.


Before April 2019 (old)

See the plugin:

https://github.com/carhartl/jquery-cookie

You can then do:

$.cookie("test", 1);

To delete:

$.removeCookie("test");

Additionally, to set a timeout of a certain number of days (10 here) on the cookie:

$.cookie("test", 1, { expires : 10 });

If the expires option is omitted, then the cookie becomes a session cookie and is deleted when the browser exits.

To cover all the options:

$.cookie("test", 1, {
expires : 10, // Expires in 10 days

path : '/', // The value of the path attribute of the cookie
// (Default: path of page that created the cookie).

domain : 'jquery.com', // The value of the domain attribute of the cookie
// (Default: domain of page that created the cookie).

secure : true // If set to true the secure attribute of the cookie
// will be set and the cookie transmission will
// require a secure protocol (defaults to false).
});

To read back the value of the cookie:

var cookieValue = $.cookie("test");

UPDATE (April 2015):

As stated in the comments below, the team that worked on the original plugin has removed the jQuery dependency in a new project (https://github.com/js-cookie/js-cookie) which has the same functionality and general syntax as the jQuery version. Apparently the original plugin isn't going anywhere though.

how to save data in a cookie using jquery

$(".esc-policy  a").on('click',function(){
var name = $("#nameInput").val(),
description = $("#descriptionInput").val();
$.cookie('back_to_url_onPage_referesh', 1);
$.cookie('name',name);
$.cookie('description',description);
});

If you add this code it will work as it is in your js. if you don't use cookie plugin in jquery. use native document.cookie expression, or extend jquery object with cookie function

you can use this plugin
https://code.google.com/p/cookies/wiki/Documentation#With_jQuery

Can jQuery read cookies?

Here is a cookie plugin for jquery https://github.com/carhartl/jquery-cookie

jQuery $.cookie not reading cookie set by server response

The problem is that the server side is sending the cookies with the HttpOnly setting as described here: http://en.wikipedia.org/w/index.php?title=HTTP_cookie#HttpOnly_cookie

Cookies sent this way are not accessible thru document.cookie. This is generally used to help protect the cookie value against possible XSS attacks on your site.

Edit: You didn't mention which technology you're using on the server side to set the cookies. In case you're using PHP, this link lists the possible ways the HttpOnly flag could be set:

https://www.owasp.org/index.php/HttpOnly#Using_PHP_to_set_HttpOnly

Setting cookie on Internet Explorer browser using JQuery

It seems that you are using the jquery-cookie plugin, please include jquery-cookie.js script after the jQuery library. You could download the jquery-cookie.js from this link.

Also, you could create a .js file with the following content, and add the file reference after the jQuery library.

juery-cookie.js

/*!
* jQuery Cookie Plugin v1.4.1
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2006, 2014 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD (Register as an anonymous module)
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {

var pluses = /\+/g;

function encode(s) {
return config.raw ? s : encodeURIComponent(s);
}

function decode(s) {
return config.raw ? s : decodeURIComponent(s);
}

function stringifyCookieValue(value) {
return encode(config.json ? JSON.stringify(value) : String(value));
}

function parseCookieValue(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}

try {
// Replace server-side written pluses with spaces.
// If we can't decode the cookie, ignore it, it's unusable.
// If we can't parse the cookie, ignore it, it's unusable.
s = decodeURIComponent(s.replace(pluses, ' '));
return config.json ? JSON.parse(s) : s;
} catch(e) {}
}

function read(s, converter) {
var value = config.raw ? s : parseCookieValue(s);
return $.isFunction(converter) ? converter(value) : value;
}

var config = $.cookie = function (key, value, options) {

// Write

if (arguments.length > 1 && !$.isFunction(value)) {
options = $.extend({}, config.defaults, options);

if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
}

return (document.cookie = [
encode(key), '=', stringifyCookieValue(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}

// Read

var result = key ? undefined : {},
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all. Also prevents odd result when
// calling $.cookie().
cookies = document.cookie ? document.cookie.split('; ') : [],
i = 0,
l = cookies.length;

for (; i < l; i++) {
var parts = cookies[i].split('='),
name = decode(parts.shift()),
cookie = parts.join('=');

if (key === name) {
// If second argument (value) is a function it's a converter...
result = read(cookie, value);
break;
}

// Prevent storing a cookie that we couldn't decode.
if (!key && (cookie = read(cookie)) !== undefined) {
result[name] = cookie;
}
}

return result;
};

config.defaults = {};

$.removeCookie = function (key, options) {
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};

}));

Html content (please remember to change the path):

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="Scripts/jquery.cookie.js"></script>

<script type="text/javascript">
$(function () {
$.cookie("myKey", "myValue");

$("#content").html($.cookie("myKey"));
});

</script>

unable to store data in browser cookie with Name and value

Issue is resolved for JavaScript.

Here is the solution for JavaScript.

    //JavaScript cookie Logic
function cookiemethod() {
document.cookie = 'JSCookieName' + "=" + 'sudheer Kumar';
}

If we written the code like this JSCookieName is name of the cookie and next is the cookie value.

Here is the output with cookie Name for Java Script

Need to find solution for Jquery cookie



Related Topics



Leave a reply



Submit