Web Development Blog

Twitter

20 Feb, 2009

Store login information in cookie using jQuery

Web Development » Snippets, Tutorials » Store login information in cookie using jQuery

HTML code:

<form action="login.php" method="post" id="login">
<fieldset>
<legend>Login</legend>
<label for="username" class="label">Username</label>
<input type="text" name="username" id="username" class="text" maxlength="30" />
<label for="password" class="label">Password</label>
<input type="password" name="password" id="password" class="text" maxlength="30" />
<input type="checkbox" name="remember" id="remember" />
<label for="remember">Remember me</label>
<input type="submit" name="submit" value="Login" />
</fieldset>
</form>

Javascript code:

The first javacript snippet will be used to store username and password into cookie if ‘Remember me’ checkbox is ticked.

The second javacript snippet will be used to populate username and password fields with the details stored in cookie previously.

Uses jQuery library and jQuery cookie plugin.

Store into cookies

if ($('#remember').attr('checked')) {
var username = $('#username').attr("value");
var password = $('#password').attr("value");
// set cookies to expire in 14 days
$.cookie('username', username, { expires: 14 });
$.cookie('password', password, { expires: 14 });
$.cookie('remember', true, { expires: 14 });
} else {
// reset cookies
$.cookie('username', null);
$.cookie('password', null);
$.cookie('remember', null);
}

Read from cookies

var remember = $.cookie('remember');
if ( remember == 'true' ) {
var username = $.cookie('username');
var password = $.cookie('password');
// autofill the fields
$('#username').attr("value", username);
$('#password').attr("value", password);
}

Recommended Books on jQuery

Other similiar posts that you might be interested in:

18 Responses to "Store login information in cookie using jQuery"

1 | Sam

February 23rd, 2009 at 1:54 am

Avatar

This is great! Thanks so much. Hope it will continue.

you can get interesting post about web usability and technology on my Web Usability Blog.

2 | Daya Shankar Kumar

February 25th, 2009 at 5:40 am

Avatar

Hi,

My requirement is almost same where if user will check remember me once then he will get his username automatically in text box.

I have used the same code, But for some reason it is not working in my asp.net mvc application. For your reference i am keeping my code which is as follows.

Login
Username

Password

Remember me

if ($(‘#remember’).attr(‘checked’)) {
var username = $(‘#username’).attr(“value”);
var password = $(‘#password’).attr(“value”);
// set cookies to expire in 14 days
$.cookie(‘username’, username, { expires: 14 });
$.cookie(‘password’, password, { expires: 14 });
$.cookie(‘remember’, true, { expires: 14 });
} else {
// reset cookies
$.cookie(‘username’, null);
$.cookie(‘password’, null);
$.cookie(‘remember’, null);
}

var remember = $.cookie(‘remember’);
if (remember == ‘true’) {
var username = $.cookie(‘username’);
var password = $.cookie(‘password’);
// autofill the fields
$(‘#username’).attr(“value”, username);
$(‘#password’).attr(“value”, password);
}

First time when page is loading username and password is coming as null. Even when i am putting username and password and do check “Remember me”, then also next time i am getting null value in both the field(username and password).

Any help would be appreciated….

Thanks in Advance…..

3 | eisabai

February 25th, 2009 at 10:27 am

Avatar

Hi Daya, Did you have your input ids as “username”, “password” and “remember” in your login form? And are you storing the cookies on onsubmit event?

4 | Daya Shankar Kumar

February 27th, 2009 at 12:54 am

Avatar

Hi Eisabai,

Thanks for your response. Yes I am using input id’s username(Textbox), password(textbox), remember(checkbox).

But I am not storing the cookies onsubmit event. Can u please guide me that how i can store cookies on onsubmit event….

Again thanks for your kind response..

Looking for your positiver response.

5 | eisabai

February 27th, 2009 at 11:49 am

Avatar

Hi Daya, you will need to put the ’store into cookies’ snippet inside your function for onsubmit event. An example on javascript onsubmit event can be found here: http://www.w3schools.com/jsref/jsref_onSubmit.asp

6 | cutie

March 8th, 2009 at 2:56 am

Avatar

hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii

7 | Malohe

March 27th, 2009 at 5:44 am

Avatar

Hi… I need help, please… I have a error, below:

jQuery is not defined
jQuery.cookie = function(name, value, options)

Help please…

8 | Malohe

March 27th, 2009 at 6:45 am

Avatar

Don’t worry, was my mistake.
Sorry :(

9 | eisabai

March 28th, 2009 at 8:10 pm

Avatar

No prob! Glad you got it sorted out.

10 | Ben Chapman

April 7th, 2009 at 11:52 am

Avatar

Terrific!

Thanks for this.

11 | Jeottelak

April 8th, 2009 at 4:14 am

Avatar

mm… bookmarked )

12 | Nitin Sawant

May 18th, 2009 at 5:44 pm

Avatar

thanks a lot, it really helped me

13 | Ben Baker

June 9th, 2009 at 5:37 am

Avatar

Hey, thanks for the code!

Works a charm. Although isn’t it a bad idea to store the users password unprotected in a cookie?

Is there any encryption that can be applied?

B ;)

14 | eisabai

June 9th, 2009 at 12:35 pm

Avatar

Hi Ben,

You can set the secure flag for the cookies so they are only transmitted via secured connections (SSL).

For example:

$.cookie(‘username’, username, { expires: 14, secure: true });

15 | Ben Baker

July 14th, 2009 at 11:54 pm

Avatar

Hey eisabai,

That’s good to know regarding secure transmit of data, but as far as I understand it the cookie is stored locally, on the users machine, right?

So you are storing the users password unencrypted in a cookie, which can be accessed and viewed.

I was thinking more along the lines of MD5 cryptography for the password/string? see here: http://pajhome.org.uk/crypt/md5/

B ;)

16 | eisabai

July 15th, 2009 at 11:45 am

Avatar

Hi Ben,
I agree it’s a good practice to encrypt cookies that contain sensitive information like username and password. Thank you for the link. :)

17 | Ben Baker

July 16th, 2009 at 10:01 pm

Avatar

Hey,

Been looking into this a bit more.

There’s a jQuery MD5 script here: http://www.semnanweb.com/jquery-plugin/md5.html

I think storing the encrypted MD5 password in the cookie then matching that to the password in the db via an MD5 comparison.

So as an example jQuery to PHP query:

jQuery:
// get user name and passwrord values
var user = $(“#user_name”).val();
var pwd = trim( $(“#user_pwd”).val() );

// make ajax call with data
$.ajax({
type: “POST”,
url: “login.php”,
data: ‘user=’+ user + ‘&pwd=’ + $.md5( pwd ),
success: loginResponse
});

php:

// get password from post vars
$pwd = mysql_real_escape_string( $_POST['pwd'] );

// query string – using sql md5()
$query = “SELECT `user_password` FROM `tbl_users `WHERE MD5( `user_password` ) = ‘”.pwd.”‘” ;

// now run query…

On a successful match you can then store you cookie data, storing the password as md5.

I think this is a good way to do it. :)

18 | Will

August 31st, 2009 at 2:50 am

Avatar

Just wanted to say that I agree with the argument that storing usernames and passwords in cookies is not good practice, even if they are encrypted with something like md5.

If you’re using php a better way to authenticate would be to use sessions and have the server set a variable in the $_SESSION array. You might also want to set a initial login timestamp value in that array, as well as a “last action” timestamp, and write your security rules based on these.

Another way of doing security in an *AMP environment is to store that data in a database table (currently logged in users) and use the session key (which is stored in a cookie or can be appended to the url if cookies are off). This is the method that expression engine uses and is quite secure.

You can then set up your rules on the server side so users are prompted for passwords more or less frequently, according to the level of security you need.

Comment Form

ebook
Subscribe to our newsletter and receive FREE e-book "7 Days Exercise to Build More Traffic To Your Blog"
Your name:  
Your email:  

  • About
    The blog Web Development Blog is where I keep myself up to date with the latest technologies in the industry and share my ideas and thoug...
  • Adsense Tips and Tricks
    With personal and commercial blogs, community websites, and social pages becoming the hot topic of the Internet in the last few years, many...
  • Advertise With Us
    Web Development Blog is a blog about Web Development, Web Design, Web Applications, Web 2.0, AJAX, Search Engine Optimisation, Latest Techno...
  • Archive
    Grab yourself a cup of coffee or tea, sit back and browse through an archive of all the blog posts on Web Development Blog....
  • Choosing a Content Management System
    The most commonly asked question when it comes to Content Management System is whether to build or buy (pre-built). While there are many fa...
  • Coupons
    Use the following coupon codes, promos and discount codes to save money on web hosting, domain names, website templates, ebooks, software, p...
  • Customised WordPress Themes
    If you would like a customised WordPress theme for your blog or your website, read on: (or head to WordPress Themes page to get free WordPre...
  • Favourite Poems
    If by Rudyard Kipling If you can keep your head when all about you Are losing theirs and blaming it on you, If you can trust yourself w...
  • Favourites
    Books Web Development Books Magazines Glamour Reader's Digest Software Adobe Photoshop CS4 Trend Micro Antivirus + Antispyw...
  • How to Start a Blog?
    What's a blog? According to Wikipedia, a blog is a user-generated website where entries are made in journal style and displayed in a reve...
  • Introduction to JSP Standard Tag Library (JSTL Basics)
    Tag libraries to include in your .jsp page <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> &l...
  • Links
    Free Anonymous Proxy Increases your privacy and security on the Internet by using our free, fast and easy to use web proxy. data backu...
  • Making a Passive Income Online
    Passive income, in my opinion, means an income which does not require a lot of regular maintenance work or continuing effort. I have been t...
  • Online Distribution Channels
    One of the importances of any website or business is to bring your products or services to the right people and to reach the target audience...
  • Recent Projects
    Followings are some of the recent projects I have done in 2006 -- 2007. Check out my latest business venture Web design Sydney to get your...
  • Recommended Web Development Books
    Many developers often ask me what books I read and what books I recommend in regards to web development and web technologies such as AJAX, J...
  • Search
    Looking for something on Web Developement Blog? Use this search tool powered by Google Custom Search to find what you are looking for just ...
  • Seven Tips to Building an Online Presence for your Business
    1. Get a domain name for your business The first and foremost step in building an online presence is to secure a domain name for your busi...
  • Seven Tips to Increasing Your Website’s Traffic Using SEO
    SEO is the buzz word - many people have mentioned it and many have heard of it too, but very few people know how to implement it properly. ...
  • Subscribe
    Newsletter [newsletter] RSS 2.0 feeds Entries feed Comments feed Subscribe using your favourite web-based or desktop feed r...
  • Useful Linux Commands
    Find files older than 60 days find * -mtime +60 Delete files in backup folder which are older than 60 days rm -f `find /backup/ -mtime ...
  • Web Design Tips
    Nowadays, having a website for your business is like having a phone number. Almost every business has their own website, with their own doma...
  • Web Development Books
    Many developers often ask me what books I read and what books I recommend in regards to web development and web technologies such as AJAX, J...
  • Web Hosting Comparison Chart
    The following are some of the most popular web hosting providers. I have personally used the recommended ones. Hosting coupon codes will ...
  • Web Standards
    Web Standards is defined as a set of rules or specifications that should be followed when developing a website.  The main objectives o...
  • WordPress Themes
    All WordPress themes are designed and coded by esn studio, and licensed under GPL license. If you would like a customised WordPress theme fo...
  • Sam: Useful. I always forget the rel target one
  • Chronic Tinnitus: Hi, Thanks for taking the time to discuss a really confusing matter - I find Plesk so much more awkward than the cpanel that I'm used to. Thanks Chr
  • Serhiy: I personally liked the web hosting comparison chart. Especially the recommended *. I got Bluehost :) .-= Serhiy´s last blog ..

Interests

Web development, Web design, Open source technologies, Portal development, APIs, Web services, Social media applications, Search engine optimisation, Mobile application development, iPhone Apps, Web 2.0, Web 3.0, Latest Internet technologies

Misc.

  • bluehost Hosting $6.95/month
  • Joomla Templates