Learn How to Work with jQuery Cookies

jquery cookieEvery time you are visiting a website, web browsers generate a unique session. Cookies are used to keep these sessions organized for each user. These are usually handled in the back-end with languages like PHP or Ruby. jQuery however, has a newer library that can simplify how it is done – with a jQuery Cookie. In this article, you will be learning how to create cookies, retrieve cookies as well as delete them.

New to jQuery? Take a class at Udemy.com.

What is a Cookie?

Before cookies were developed, servers had no way to know whether requests they received came from the same web browser. This made it difficult for them to keep track of sessions and users, especially for websites that require logging in. This is why cookies were created and adopted as client-side storage.

Cookies are small and often encrypted text files, which are used by web developers to allow users to navigate their websites more efficiently. They are created when a user loads a certain website, which sends information to the browser for saving.  As long as these cookies exist, every time the user loads the same website, his session data is preserved. Some of the functions regulated using cookies are keeping users logged in (remembering their sign-in data), regulating how ads appear and managing how widgets or plug-ins work.

jQuery Cookies

Compared to regular JavaScript, setting, retrieving and deleting cookies are relatively really easy. However, a jQuery Cookie is not included in the jQuery core by default. To start with, you will have to download and install the jquery.cookie library.

You can download the library from its GitHub repository here: https://github.com/carhartl/jquery-cookie

When you have the jquery.cookie.js, you will simply need to add it in your website pages. Include it after the jQuery library using code like:

 

<head><scriptsrc=”sourcepath/to/jquery.js”></script><scriptsrc=”sourcepath/to/jquery.cookie.js”></script></head>

 

After setting everything up, you are now ready to learn how to create, retrieve and delete cookies. There is one method used to both create and retrieve a cookie – cookie(). The difference between creating and retrieving relies on the parameters that you will be passing to the cookie() method.

Need to know jQuery In depth functions? Take a course at Udemy.com.

Creating a Cookie. There are 2 required parameters if you want to create a cookie:  name and value. The third parameter is optional – an object literal with additional options (path, domain, expires, secure).

Examples:

$.cookie("visits", 21);

This code shows an example of the cookie() method with the 2 required parameters. The function of which is to track the number of times a user has visited a website. The first parameter “visits” is the name and the second parameter 10 is the value.

$.cookie("favorite-food", "Fries", {path: "/", domain: "jssample.com"});

In this example, the code made use of the 2 required parameters as well as the optional object literals, path and domain. “favorite-food” is the name, “Fries” is the value and the statement enclosed in the brackets with the path and domain keywords is the literal path where the cookie can be read and written.

path: “/” means that you’re explicitly declaring that your cookie is available for all paths in your domain. To limit the access, you can use a specific path like path: ‘/admin’. By default, the cookie’s path is the path of the page in which the cookie was created.

$.cookie("name", "John", {expires: newDate(2014, 04, 29, 11, 00, 00)};

This one also includes the required parameters name and value, as well as the optional literal, expires. The expires option allows you to control when the cookie you have created expires. In this case, it was specified as April 29, 2014 11:00:00.

$.cookie("name", "John", {secure: true});

Using the same example above, with the exception of the optional literal secure, it has been specified that the created cookie can only be sent through a secure network (secure protocol – https).

Retrieving a Cookie. To get cookies is really easy. You will only need to use the same code, cookie(), but with only one parameter. The parameter you’ll be passing is the cookie name and then the method will return to you its respective value.

Examples:

console.debug($.cookie("visits"));

The console.debug code prints the retrieved value from the cookie with the name “visits”. According to the first example in creating a cookie, the value for the cookie is ‘21’. This will now be printed.

console.debug($.cookie("favorite-food"));

If you print the cookie for “favorite-food” you will get the value “Fries” as specified above.

Removing a Cookie. You now know how to create and retrieve cookies. However, once you’re done using them and you have no more plans of using them again, you should delete them, instead of letting them clutter the disk. To do this, you only need to use the code removeCookie(). It returns ‘true’ if the specified cookie is found and ‘false’ if the request fails to find it. However, always remember that if you created a cookie with options, you will also need to specify those options when you remove that cookie.

Want to learn more about jQuery? Take a course at Udemy.com.

Examples: 

$.removeCookie("name");

This will delete the file for the cookie with the name “name”.

$.removeCookie("favorite-food", {path: "/", domain: "jssample.com"});

This will delete the cookie with the name “favorite-food” which can be found in the specified path.

$.removeCookie("favorite-food”);

If you only use this code to delete the cookie “favorite-food”, the method will return ‘false’ because without the specified path, the cookie won’t be found and therefore won’t be deleted.

Using cookies can be very helpful not only in terms of organizing sessions and log-in data for the users, but also in systematizing other data like ecommerce data (using unique cookie IDs). Notice that more and more online shopping sites are continuing to multiply and evolve. Advancements in web development and its tools have made it easier and easier to set them up. Aside from these, there are endless other possible uses for cookies and the jQuery Cookie has made it very convenient to manipulate and process cookies for whatever purpose you may need them for.