Jquery cookie lifetime. Top jQuery plugins

Web browsers can generate unique sessions specific to each user on a site. Often this process is implemented in the backend using languages ​​such as PHP or Ruby, but we can also use session cookies on external interface at javascript help. There are many tutorials out there that tell you how to generate pure JS cookies. But the new jQuery Cookies library makes the process much easier.

Let us tell you how, with help, you can realize very simple system authentication. All code will be presented on the front end, but in order to see the results of the work, you will need a live server for testing. Browser cookies will be created on the local IP offered by the web server, which means that unfortunately you will not be able to run these scripts locally. Don't forget to check out the live demo to see what we're talking about.

Attention! You do not have permission to view hidden text.

Document basis

To begin, we'll create a sample HTML5 document with a single reference to the jQuery library, as well as the jQuery Cookies function. You can download them directly, and the only file we will need is jquery.cookie.js.






Managing Cookies with jQuery - Live Demo







The tutorial will focus on creating two different views for the page. First we will have a login form that will be displayed if there is no cookie. Using standard values demo/demo, you can log in using the form and it will save your session in a cookie.

Obviously, if you connect the script to the database, you will be able to serve big number logins. This means that with a single script you can authorize many people, and at the same time store their logins or IDs in local cookies. This example is just a starting point where we don't need Ajax requests or server side scripts to authorize users.

Inner element content

The first div is the wrapper that contains the entire page. There is a form with ID #loginform that is displayed first. It will be hidden using jQuery only if the visitor is on this moment logged into a demo account using a session cookie.



Basic Cookie Management

Login to the demo account with the following username/password: demo/demo


Username:

Password:




You are logged in as demo! The cookie is set to expire in 1 day from the original login.

Want to logout? Easy!

Logout Now





You probably noticed that in the HTML after the login form there is another div with the id #logindetails. We hid it using CSS styles, since we need it to be displayed to the user only if he is logged in. The internal HTML is static and always displays the demo username. But when working with a database, you can update this parameter to any username using javascript.

CSS styles aren't that complicated, but it would be nice to go into some detail. We created a glossy CSS3 button using tips from the tutorial. These styles are quite extensive and should be saved for reuse in other projects.

/** form elements **/
form label ( font-size: 1.1em; line-height: 1.25em; font-weight: bold; margin-bottom: 5px; )

form input.basic (
display: block;
outline: none;
font-size: 1.5em;
color: #525252;
width: 300px;
padding: 10px 8px 10px 8px;
margin-bottom: 7px;
border: 1px solid #888;
border-radius: 5px;
-webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,0.4);
-moz-box-shadow: inset 0 1px 2px rgba(0,0,0,0.4);
box-shadow: inset 0 1px 2px rgba(0,0,0,0.4);
}

#logindetails (
display: none;
}
We also changed standard elements input so that they fit better with the page. The login details container is marked with the display: none property, so it won't take up any space on the generated page. However, it still makes up the active part of the DOM, which means we can manipulate the display value using jQuery. Now let's take a look at this jQuery code located at the bottom of the page, just before the closing body tag.

Cookies in jQuery

The plugin offers us several standard features, which may require a lot more logic in regular javascript. Here are pre-prepared internal methods to call new cookies and delete existing ones. Let's take a look at the opening block of code to understand what's going on here:

$(function())(
if($.cookie("username")) (
$("#loginform").hide();
$("#logindetails").show();
}
Undoubtedly, there are more good ways managing this form using internal interface languages, but in our demo jQuery does a great job. By running the if statement against $.cookie(‘username’), we check to see if the “username” cookie exists. If yes, then we know that the user is currently logged into their account, so we hide the authorization form and show login information. Otherwise, nothing happens and we just see a page with a login form.

$("#loginform").submit(function(e)(
e.preventDefault();
var inputuname = $("#username").val();
var inputpass = $("#password").val();

If(inputuname == "demo" && inputpass == "demo") (
// successful validation and create cookie
$.cookie("username", "demo", ( expires: 1 ));
var currentusr = $.cookie("username");
window.location.reload();
}
});

$("#logoutbtn").on("click", function(e)(
e.preventDefault();
if($.removeCookie("username")) (
$("#logoutcontainer").html("Successfully logged out! Refreshing the page now...");
window.setTimeout("location.reload()", 2000); // refresh after 2 sec
}
});
});
We have combined these two functions into single block code, since they are very similar to each other. As soon as the user attempts to log into the account, we check if the username/password matches “demo”. If yes, then we run $.cookie('username', 'demo', ( expires: 1 ));, which includes several options.

First we assign a cookie name “username”, against which we can check the value. The string “demo” is the cookie value, but it is important to remember that we can enter any username or even id if this method would otherwise be more appropriate. Finally, last parameter is a collection of options that sets the number of days before the cookie expires. If we omit the expiration option, then the cookies will be deleted as soon as the user closes the browser. This is also mentioned in the session cookie and below we have provided a simple example commented at the bottom of the script.

The second block of code tracks the user's clicks on the #logoutbtn link. Obviously, the logout link will only be displayed if the user is currently logged in. This function will terminate the session by running $.removeCookie('username') inside an if statement. So if we can remove the cookie, then we need to remove the logout button and show a success message and present the login form.

In conclusion

Cookies are very convenient for storing information about authorization and for other purposes. You can organize an online store that runs on sessions in the backend using unique id cookies. Online stores are very popular today, and developments in web development make them much easier to organize and maintain. You can download the code example and check how you can use this example in your own projects, and also try to improve the functionality.

It's probably worth starting with what cookies are and what they are needed for. A cookie is a piece of data that can be stored on the user’s side and used later to implement their ideas.

Let's imagine that on your website you have the opportunity to choose color scheme site. It is very convenient to implement this on cookies, since the theme he selects will be visible only to him.

Cookies exist in both PHP and jQuery. Therefore, we will consider each case in more detail.

Detailed instructions for working with Cookies in jQuery

1. Setting Cookies

Now we can try to create our first cookie:

$.cookie("cookie_name", "cookie_value", ( expires: 3, path: "/", domain: "your_site.ru", secure: true ));

What's what here?

“cookie_name” – cookie name;

“cookie_value” – cookie value;

“expires” – the number of days the cookies will be stored (in our case – 3 days). After this time, it will happen automatic removal cookies;

“path” – availability of cookies on the site (in our case “/” - available on the entire site). If desired, you can only set specific page or the section where the cookie will be available, for example, “/audio/rock”;

“domain” – the domain on which the cookie is valid. If you have a subdomain, you can specify it in this parameter, for example, “domain: “subdomain.your_site.ru””, and in this case the cookie will only be available on the domain “subdomain.your_site.ru”;

“ secure" – a parameter indicating that the cookie should be transmitted securely https protocol.

Here, not all parameters are required, and in order to set cookies, this construction will be sufficient:

$.cookie("cookie_name", "cookie_value", ( expires: 3, path: "/" ));

2. Receiving a Cookie

Getting cookies is quite simple; you can do this using the code:

$.cookie("cookie_name");

This code can be assigned to a variable and used for your needs:

var content = $.cookie("cookie_name");

if(content != null) ( alert("Cookie exists!"); ) else ( alert("Cookie does not exist!"); )

3. Agree, this is very convenient.

To remove a cookie value, set it to "null":

$.cookie("cookie_name", null);

This, I think, is the end of the introduction to working with Cookies in jQuery. This knowledge is quite enough to implement your ideas.

Detailed instructions for working with Cookies in PHP

Unlike the previous option for working with cookies, you don’t need to connect anything here.

1. Setting Cookies

In order to set cookies in PHP, we will use the built-in “setcookie” function:

What's what here?

“cookie_name” – cookie name;

“cookie_value” – cookie value;

“time()+3600” – cookie lifetime in seconds (in our case – 1 hour). If you set the lifetime to “0”, the cookie will be deleted as soon as the browser is closed;

“/” – the section in which cookies are available (in our case, available throughout the site). If you want to limit the section in which cookies will be available, then replace “/” with, for example, “/audio/rock”;

“your_site.ru” – the domain on which the cookie will be available;

“true” – a parameter indicating that the cookie is only available via the secure https protocol. Otherwise the value is false ;

“false” – parameter indicating that the cookie is available scripting languages. Otherwise – true (available only via http).

Here, too, not all parameters are required, and to create cookies you will only need the following construction:

For convenience, the cookie value can be set via a variable:

2. Receiving a Cookie

In order to receive cookies, you need to use:

$_COOKIE["cookie_name"];

To prevent errors from occurring due to possible absence cookies, use:

As in the previous example of working with Cookies in jQuery, cookies can be assigned to a variable:

3. Agree, this is very convenient.

Removing cookies in PHP is just as easy as in jQuery. All you have to do is set the cookie to an empty value and a negative time (time that has already passed):

Setcookie("cookie_name", "", time() - 3600);

Time in in this example equal to an hour ago, which is quite enough to delete cookies.

I would like to note that in some cases, using cookies is much more rational than using a database to implement the necessary functionality.

When I was learning PHP I often needed to use cookies and sessions to remember intermediate calculations entered by the user. When I found out that jQuery has a special plugin that allows memorizing values ​​using the same principles, my scripts became much simpler.

The library responsible for working with cookies is called jquery.cookie.js. You can download it along with a working example below. This plugin requires installation jQuery libraries, For example, version will do 1.9.1.

jquery.cookie.js plugin parameters:

  • expires - if absent, the values ​​can be remembered until the user closes the browser. Those. Until he closes it, no matter how many times he refreshes the page, the cookies will be saved. If you specify a number, it allows you to store cookies a certain amount of days. Those. Until the time runs out, the cookies will remember the user's values.
  • path - cookies can work both on the entire site (/) and on a specific directory (/my/file/).
  • domain - domain on which the cookie will be created (current by default)
  • secure - if set to true, then the installed cookies will be sent to the server only via the https protocol (false by default)
  • The parameters listed above are optional for working with cookies. You don't have to install them. Let's look at how to install the simplest cookie.

    Setting cookies on the site

    To do this, write: $.cookie("cookie_name1", "Cookie1 value");

    From this example, we will set the cookie_name1 variable to a value that we need to remember. Also, since the storage time is not specified here, the cookie will be deleted after closing the browser.
    An example of a cookie that is valid on the entire site for 5 days

    $.cookie("cookie_name2", "Cookie2 value", (expires: 5, path: "/"));
    An example of a full cookie that, among other things, operates on a specific domain and transmits data only via https:

    $.cookie("cookie_name", "Cookie value3", (expires: 5, path: "/", domain: "site", secure: true)); ));
    Getting the cookie value
    Getting a set cookie is very simple, consider the example below - it will display a message about the set value.

    var test = $.cookie("cookie_name1"); alert(test);
    How to check if a cookie is set on a site
    To do this you need to use an if condition

    if($.cookie("cookie_name1")) alert(test);
    Removing cookies
    This operation amounts to clearing the cookie value to zero.

    $.cookie("cookie_name2", null);