In this post I want to show you how to use jQuery to create an AJAX login screen. I am going to use an ASP.NET MVC application for this demonstration. I will be modifying the small default application that is created when you create a new MVC application. So go ahead and create a new MVC application. I will be walking through the process step by step so when this article is done you will have a working application.

create-mvc-app

Step 1

Open LogOnUserControl.ascx. This is found in /Views/Shared/. What we want to do is modify the link to include an onclick attribute which will fire the login() event handler and assign an id to the link. The code should look like this:

 

   1: <%= Html.ActionLink("Log On", "LogOn", "Account", null,
   2: new { onclick = "return login();", id = "login_link" })%>

 

Step 2

Open the Site.Master master page, also located in /Views/Shared/, add  the links to our stylesheet, jQuery, and our JavaScript file in the head section of the document.

   1: <link type="text/css" rel="stylesheet" href="../../Content/login.css" />
   2: <script type="text/javascript" src="../../Scripts/jquery-1.2.6.min.js"></script>
   3: <script type="text/javascript" src="../../Scripts/login.js"></script>

Go ahead and create a login.css file in /Content/ and a login.js file in /Scripts/. Leave them empty for now.

 

Step 3

While still in Site.Master, add the following code at the bottom of the page, just before the closing body tag. This is our login form that we will use. The code contains a div element with the id lightbox that will cover the screen to make our login form act as a model dialog. The lightbox will be a transparent black color.

In addition to the form input elements there is also a div element called message that will server as an area for us to output messages.

<div id="lightbox"></div>
<div id="login_outer_container">
<div id="login_form">
<div id="message"></div>
<fieldset>
<legend>Login Information</legend>
<p>
<label for="username">Username:</label>
<%
   = Html.TextBox("username")

%>
<%

   = Html.ValidationMessage("username")

%>
</p>
<p>
<label for="password">Password:</label>
<%

   = Html.Password("password")

%>
<%

   = Html.ValidationMessage("password")

%>
</p>
<p>
<%

   = Html.CheckBox("rememberMe")

%> <label class="inline" for="rememberMe">Remember me?</label>
</p>
<p>
<input type="button" value="Log On" onclick="submitForm();" />
<input type="button" value="Cancel" onclick="cancelLogin();" />
</p>
</fieldset>
</div>
</div>

 

Step 4

Add the following code to login.css. This will style our form elements.

   1: #lightbox {
   2: position: absolute;
   3: top: 0;
   4: left: 0;
   5: width: 100%;
   6: background: black;
   7: filter: alpha(opacity=60);
   8: opacity: 0.6;
   9: display: none;
  10: }
  11: 
  12: #login_outer_container {
  13: position: absolute;
  14: top: 50%;
  15: left: 50%;
  16: }
  17: 
  18: #login_form {
  19: position: relative;
  20: top: -125px;
  21: left: -200px;
  22: width: 400px;
  23: height: 250px;
  24: display: none;
  25: background: white;
  26: padding: 10px;
  27: border: 1px solid #424242;
  28: }
  29: #message {
  30: display: none;
  31: border: 1px solid #b8b8b8;
  32: background: #f6f3f6;
  33: padding: 5px;
  34: color: Red;
  35: }
  36: 

 

Step 5

Alright, this is where the real magic happens. We are going to add code to login.js. I will go slow and explain what each function is doing and why it matters to our application.

The first function we are going to add is the login() event handler we mentioned earlier in the post. In this function we are getting the lightbox element and assigning some stylesheet properties to it. Notice that we are setting the filter attribute even thought we did so in login.css. For some reason IE keep losing this setting so we had to add it again. We are also telling lightbox to fade in slowly.

Next we get the main login form element and tell it to also fade in slowly.

Finally, we return false to prevent the link from jumping to it’s href value. We don’t want to cause a page refresh.

   1: function login() {
   2: $('#lightbox')
   3: .css({
   4: 'height': $(document).height(),
   5: //reset opacity because IE loses it on open 
   6: 'filter': 'alpha(opacity=60)'
   7: })
   8: .fadeIn('slow');
   9: $('#login_form').fadeIn('slow');
  10: return false;
  11: }

Now when a user clicks the [ Log On ] link an impressive login form will fade into the center of the screen.

Notice how we set the height of the lightbox to the current height of the document. If the user resizes the browser window this will cause the lightbox to be too big and add scroll bars or cause the lightbox to be too small, all depending how the window is resized. To fix this this problem we will create a function that will set lightbox to the current height of the document and setup an event handler that will fire our function every time the window is resized.

   1: function adjustLightbox() {
   2: $('#lightbox').css({ 'height': $(document).height() });
   3: };
   4: 
   5: var resizeTimer = null;
   6: $(window).bind('resize', function() {
   7: if (resizeTimer) clearTimeout(resizeTimer);
   8: resizeTimer = setTimeout(adjustLightbox, 100);
   9: });
  10: 

When we created our login form markup we added an input button that had an onclick handler called cancelLogin(). If the user clicked this button we wanted to cancel the login form, clear an input, and restore the main screen. Let’s create that function.

This function first tells lightbox and the main login form to slowly fade out which will restore the main screen.

Next we clear the value of all input elements that are not buttons and make sure the remember me checkbox is not checked.

Lastly, we clear and messages that were output and hide the message element.

   1: function cancelLogin() {
   2: $('#lightbox').fadeOut('slow');
   3: $('#login_form').fadeOut('slow');
   4: $('#login_form input[type!=button]').val('');
   5: $('#login_form input[type=checkbox]').each(function(i) {
   6: this.checked = false;
   7: });
   8: $('#message').html('').css({ 'display' : 'none' });
   9: }

This brings us to out last function which will submit the form when the user clicks submit. First create the submitForm function. This function has been assigned to the submit button’s onclick handler in our HTML.

   1: function submitForm() {
   2: 
   3: }
   4: 

The first thing we need to do is get the values from our three form elements, username, password, and remember me.

   1: var username = $('#username').value;
   2: var password = $('#password').value;
   3: var rememberMe = $('#rememberMe').checked ? 'true' : 'false';

At this point you can do any form validation you want against the values. I am not going to include any validation in this demonstration.

Next we’ll build a data string out of our three values.

   1: var dataString = 'username=' + username + '&password=' + password + '&rememberMe='
   2:  + rememberMe;

Finally we will setup our AJAX call to the server to authenticate the user. We will use the data string we just setup as the data to pass to the request. We have also setup success and failure callbacks.

If the request succeeds we will call the cancelLogin() function to close the login form and change the Log On link to say Log Off.

If the request fails, we’ll show the user an error message.

   1: $.ajax({
   2: type: 'POST',
   3: url: '/Account/LogOn',
   4: data: dataString,
   5: success: function() {
   6: cancelLogin();
   7: $('#login_link').html('Log Off').href = '/Account/LogOff';
   8: },
   9: error: function() {
  10: $('#message').html('Failed to login')
  11: .css({ 'display': 'block' });
  12: }
  13: });

That pretty much finishes things off. you should now have a working login form. Stayed tuned for more great posts from Dev102.com by grabbing the RSS feed. You can also see more posts I have written on my blog or grab my RSS feed.

Tags :

18 Responses to “Creating an Ajax Login Form With jQuery”


  1. Zack Owens

    Said on March 23, 2009 :

    How about a little MD5 encryption of that password? There’s some javascript implementations floating around.

  2. noob

    Said on March 24, 2009 :

    how about a demo page

  3. Pk

    Said on March 25, 2009 :

    Where’s Demo?

  4. Luiz

    Said on March 25, 2009 :

    I’ve translated your post to portuguese.

  5. trendbender

    Said on March 26, 2009 :

    ths, really helpful

  6. JeroenH

    Said on March 30, 2009 :

    Nice post.

    I agree with Zack about the encryption though. And I have one other remark: your initialization code of the login link kind of violates the ‘unobtrusive javascript’ principle.

    I think a better way would be to initialize the code on document ready:

    $(function() {$(‘#login_link’).click(login); });

  7. Jon

    Said on April 22, 2009 :

    What if a user has JavaScript turned off? Should we code for that these days or do you think we can assume JavaScript will be available, seems to double the workload if you try and handle for it not being available?

  8. xOxo

    Said on May 12, 2009 :

    wtf???

    var rememberMe = $(‘#rememberMe’).checked ? ‘true’ : ‘false’;

    is like that

    var rememberMe = $(‘#rememberMe’).checked ? true : false;

    logical operators is not a string… never

  9. Jose

    Said on July 8, 2009 :

    Sorry there is no Demo….

  10. Ay?egül

    Said on October 27, 2009 :

    Hi,
    I take an error on submitForm()
    “Microsoft JScript runtime error :Object is expected.”

    how can I solve this problem.

    Kind regards.

  11. dedek

    Said on February 21, 2010 :

    where is demo page?

  12. balda

    Said on August 7, 2010 :

    Where is the DEMO page????

  13. Adam

    Said on September 3, 2010 :

    In case anyone’s trying to get this working with MVC 2, make sure you reference the correct version of jquery – the one included is a later version than that included with MVC 1

    So change

    to

  14. bxbenny

    Said on February 7, 2011 :

    Passing username and password via url is NOT secure.

  15. jino

    Said on September 23, 2011 :

    i am trying the same with php.can anyone help me?amtrying to login using jquery lightbox onload fn.

  16. nadeekadn

    Said on April 6, 2012 :

    very helpful article. thanks for sharing.. (Y)

  17. radyo dinle zergan

    Said on March 24, 2014 :

    Hello my loved ?ne! I ?ant to ?ay that thi?
    article is amazing, nice written ?nd c?me with almost all impo?tant
    infos. I’d l?ke to peer m?re posts l?ke this .

1 Trackback(s)

  1. Mar 25, 2009: links for 2009-03-25 « pabloidz

Post a Comment