Thursday, 20 March 2014

create cookie jquery

Cookies – it used to maintain the application data in user system, as HTML is stateless protocol we need to maintain the data. It is not good option to maintain it in user system but some time we have to do it.

It easy to implement cookies in user system;
First need to download the cookies js files; Once you got the file take the reference on your application(aspx or html page);
  <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery.cookie.js"></script>

Call method to perform operation for cookies

Create cookies in query
To create or to retrieve the cookies from jquery we need to call the method .cookie, you need to pass the two required parameter, the name and the value of cookie respectively.
  $.cookie("userCount", 8);
Passing some domain URL
 $.cookie("favourite-city", "Delhi", { path: "/", domain: "" });
Suppose if you want to set the expiration for user cookies than you need to defined date and time:
$.cookie("name", "bob", { expires: new Date(2013, 10, 16, 12, 00, 00), secure: true });

Retrieve cookie
To retrieve the cookie you need to use the same method, here you just need to pass the key and it will return the value;
console.debug($.cookie("userCount")); // return 8

Delete Cookies
last thing is you need to delete a cookie using the removeCookie(), it return true; Be attentive that if you are removing a cookie, you have to pass in the same options, like path  and domain otherwise the operation will fail.
$.removeCookie("userCount"); // successfully deleted
$.removeCookie("favourite-city", { path: "/", domain: "" }); // successfully deleted
$.cookie("name"); // as no secure value defined 

No comments:

Post a Comment


You will like to read it