» Birthday Bundle - Over $400 worth of Envato files for just $20

How to Implement a jQuery AJAX Login Form into a Modal Box

Posted on April 24, 2009, Filled under AJAX, JavaScript,  Bookmark it

Do you need to integrate an AJAX Login Form into a Modal Box? This tutorial will show you how you can do that using the powerful library JQuery. The modal box that I’ve chosen is a JQuery Plugin written by Eric Martin.

Modal Login Boxes

Let’s start making the html file where the modal box is triggered:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Modal Ajax Login Form</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<script type="text/javascript" src="javascript/jquery.simplemodal.js"></script>
<script type="text/javascript" src="javascript/init.js"></script>

<link type='text/css' href='style/stylesheet.css' rel='stylesheet' media='screen' />

<link type='text/css' href='style/basic.css' rel='stylesheet' media='screen' />

</head>

<body>

Click the login link to launch the modal box:<br />

<span style="font-size: 15px;">
<a id="login_link" href="#">LOGIN</a> | MEMBERS AREA</a>

</span>

<div id="login_form" style='display:none'>

<div id="status" align="left" style="margin-top: 20px; width: 310px;">

<center><h1><img src="images/key.png" align="absmiddle">&nbsp;LOGIN</h1>

<div id="login_response"><!-- spanner --></div> </center>

<form id="login" action="javascript:alert('success!');">
<input type="hidden" name="action" value="user_login">
<input type="hidden" name="module" value="login">

<label>E-Mail</label><input type="text" name="email"><br />
<label>Password</label><input type="password" name="password"><br />  

<label>&nbsp;</label><input value="Login" name="Login" id="submit" class="big" type="submit" />

<div id="ajax_loading">
<img align="absmiddle" src="images/spinner.gif">&nbsp;Processing...
</div>

</form>

 </div>

</div>

</body>
</html>


In the HEAD part of the page I’ve included the JQuery library, the modal box and the AJAX Login script. When the “LOGIN” link is clicked (id=”login_link”) the modal box is triggered and the login form is shown (initially it’s hidden).

Here’s the content of init.js (I will explain you how it works below):

// Preload Images
img1 = new Image(16, 16);
img1.src="images/spinner.gif";

img2 = new Image(220, 19);
img2.src="images/ajax-loader.gif";

// When DOM is ready
$(document).ready(function(){

// Launch MODAL BOX if the Login Link is clicked
$("#login_link").click(function(){
$('#login_form').modal();
});

// When the form is submitted
$("#status > form").submit(function(){  

// Hide 'Submit' Button
$('#submit').hide();

// Show Gif Spinning Rotator
$('#ajax_loading').show();

// 'this' refers to the current submitted form
var str = $(this).serialize();  

// -- Start AJAX Call --

$.ajax({
    type: "POST",
    url: "do-login.php",  // Send the login info to this page
    data: str,
    success: function(msg){  

$("#status").ajaxComplete(function(event, request, settings){  

 // Show 'Submit' Button
$('#submit').show();

// Hide Gif Spinning Rotator
$('#ajax_loading').hide();  

 if(msg == 'OK') // LOGIN OK?
 {
 var login_response = '<div id="logged_in">' +
'<div style="width: 350px; float: left; margin-left: 70px;">' +
'<div style="width: 40px; float: left;">' +
'<img style="margin: 10px 0px 10px 0px;" align="absmiddle" src="images/ajax-loader.gif">' +
'</div>' +
'<div style="margin: 10px 0px 0px 10px; float: right; width: 300px;">'+
"You are successfully logged in! <br /> Please wait while you're redirected...</div></div>";

$('a.modalCloseImg').hide();  

$('#simplemodal-container').css("width","500px");
$('#simplemodal-container').css("height","120px");

 $(this).html(login_response); // Refers to 'status'

// After 3 seconds redirect the
setTimeout('go_to_private_page()', 3000);
 }
 else // ERROR?
 {
 var login_response = msg;
 $('#login_response').html(login_response);
 }  

 });  

 }  

  });  

// -- End AJAX Call --

return false;

}); // end submit event

});

function go_to_private_page()
{
window.location = 'private.php'; // Members Area
}

First, the GIFs are preloaded. This way they will load instantly when it’s the case:

// Preload Images
img1 = new Image(16, 16);
img1.src="images/spinner.gif";

img2 = new Image(220, 19);
img2.src="images/ajax-loader.gif";

When DOM is ready (all page elements are loaded, including graphics) the Modal Box is launched when the user clicks on the “Login” link:

// Launch MODAL BOX if the Login Link is clicked
$("#login_link").click(function(){
$('#login_form').modal();
});

When the form is submitted, the “Submit” button is hidden and the GIF spinning rotator/loader is shown:

// When the form is submitted
$("#status > form").submit(function(){  

// Hide 'Submit' Button
$('#submit').hide();

// Show Gif Spinning Rotator
$('#ajax_loading').show();

// ..................
});

The form data is serialized:

// 'this' refers to the current submitted form
var str = $(this).serialize();  

Further on, the data is sent to “do-login.php” using AJAX. If ‘OK’ is returned then a confirmation message will be shown to the user before redirecting him to the private page. Notice how I used JQuery’s css(name, value) function to change the width and height of the modal box:

 var login_response = '<div id="logged_in">' +
'<div style="width: 350px; float: left; margin-left: 70px;">' +
'<div style="width: 40px; float: left;">' +
'<img style="margin: 10px 0px 10px 0px;" align="absmiddle" src="images/ajax-loader.gif">' +
'</div>' +
'<div style="margin: 10px 0px 0px 10px; float: right; width: 300px;">'+
"You are successfully logged in! <br /> Please wait while you're redirected...</div></div>";

$('a.modalCloseImg').hide();  

$('#simplemodal-container').css("width","500px");
$('#simplemodal-container').css("height","120px");

 $(this).html(login_response); // Refers to 'status'

// After 3 seconds redirect the
setTimeout('go_to_private_page()', 3000);

If there are errors (incorrect login) they will be shown above the form (“login_response” DIV).

var login_response = msg;
 $('#login_response').html(login_response);

The design is fully customizable using CSS. Consider downloading the ZIP archive which contains all the files you need.

DEMO
- – - – - – - – - – - – - – - – -
E-Mail: demo@demo.com
Password: demo123
- – - – - – - – - – - – - – - – -

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

50 Replies to "How to Implement a jQuery AJAX Login Form into a Modal Box"

  1. Nice write-up Gabriel! Thanks for using SimpleModal – I’ll be sure to pass this along to other jQuery/SimpleModal users!

  2. Nice post. One thing to add, though, is that you should always set the href attribute to an actual login page (as in href=”login.php” instead of “href=#”) in case the user doesn’t have JavaScript activated, or the login function would be rendered useless.

    I know that this may have not been done in the demo for practical purposes, but it’s worth noting, IMO.

    Regards,
    Gonzalo

  3. nice work gabriel, most modal logins i’ve seen don’t use ajax to check login details, which isn’t great. i’m going to use this one- thanks!

    rob ganly

  4. Thanks for the useful info. It’s so interesting

  5. How do I modify this form action to work as a login modal for wordpress. I feel like that would be a huge traffic driver if you wrote an addon tutorial to make a wordpress modal login box. I have wanted to implement that for a long time but have no ajax skills. Thanks.

    1. @Leland: To do this you have to study the WordPress Login process. Your idea is quite good and I will think about implementing the WP Login in a Modal Box.

      1. Hi Gabriel,
        Any news with implementing the WP Login in a Modal Box?
        thanks

        1. I have recently written a post about a WordPress Plugin that you may find interesting: http://bit.ly/8TiEV2

  6. You have no idea how long I was waiting for something like this.

    Could never achieve such a great script. I tried…

    Thanks mate

  7. I’m new to jQuery/js, can I make multiple links in the same page trigger that function?

    1. Never mind, did some looking and figured it out…awesome.

  8. I would love to see this incorporated into wordpress. I’m looking for a way of having a modal box or something similar used for a login for a clients area I’m trying to setup.

  9. Can you please suggest examples using ASP .net instead of PHP itried to search a lot in net but recieved faiure to get the same jo as you did in PHP. Please help me to know how the same functiionality is achieved in asp .net

  10. Hi,

    Nice. But i don’t want the Modal Box launched when the user clicks on the “Login” link, i want it launched when the page loaded.

    Can anyone teach me how to do that?

    Or what should i edit this line:

    $(“#login_link”).click(function(){
    $(‘#login_form’).modal();
    });

    Thanks…

    1. You should just remove the first and the last line:

      replace

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

      with

      $(‘#login_form’).modal();

      1. Hello Gabriel,

        Thanks a lot! It works. But i don’t want show the login form as soon as the page loaded, i want to show the login form after 10 seconds. Can you teach me how?

        Thanks…

        Rex

        1. Replace the following line:

          $(’#login_form’).modal();

          with:

          setTimeout(“$(‘#login_form’).modal();”, 10000);

          Note: The timeout value is set in milliseconds. So, if you want to wait 5 seconds until the modal login launches just set the value to 5000.

          1. Hello Gabriel,

            Thanks….. It works Perfect!!! :)

            Many thanks….

            God Bless…

            Rex

  11. Thankyou, This is fantastic, thanks fro the great work!

  12. Hello Gabriel,

    I have a problem here. I removed the close button(X) at the upper left of my form, because i don’t want my users to see the content before they log in.

    I want the model window to close after they enter the correct password. I don’t want to redirect them to the private page.

    I try my best to edit the code below but cannot works. So i hope you can help. Thanks.

    In init.js, I just replace:

    setTimeout(‘go_to_private_page()’, 3000);

    to

    setTimeout(“$(‘a.modalCloseImg’).hide();”, 3000);

    Or replace here like:

    function go_to_private_page()
    {
    window.location = ‘private.php’;
    }

    to

    function go_to_private_page()
    {
    ?
    }

    Thanks,

    Good day!

    Rex

  13. hi
    i have problem, cannot redirect to private page

    please help

  14. Thanks for great work. I’m using this in one of my project……

  15. Hi, I tried the login, it seems to break in FF3.5, but works fine in IE8. Is there a bug?

  16. [...] Form de login într-o fereastră modală [...]

  17. Hi,
    not file login.php Error redirect! Please help.

  18. why do you need this:

    http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

    in the code?

    Can this box be done without having an external js link for it to work?

  19. Tuba,
    Yes, it can be done using local js libraries (by uploading it to your server). The external, Google-hosted library is used to get advantage of caching. You see, if someone has already visited a site which used the js from Google, it will be cached and it’s one less file to be downloading, improving download times and perceived speed by the user.

  20. Hello Gabriel,

    Thanks you sooo much for this post. This is is great.

    This is (almost) exactly what I was looking for.

    Here is my case:

    here is what I have now:

    default.aspx
    login.aspx
    privatepage.aspx

    from default.aspx when a user clicks on privatepage.aspx, he/she gets redirected to login.aspx?page=privatepage.aspx
    then when the user enters the correct credentials, he/she gets redirected to privatepage.aspx

    I will need to replace $(‘#login_link’).click(function(){
    $(‘#login_form’).modal();
    });
    with
    $(‘#login_form’).modal();

    but my question is where should I put this code? in privatepage? or in login.aspx?

    I don’t (of course) want to have users see privatepage.aspx before they login.

    Also, the login page uses a usercontrol that sets the session objects (fname, lname, etc.)

    Please advise.

    Thanks

    1. Just leave the code in init.js. Include the JavaScript file only in the login.aspx page.

  21. the PHP for the donload won’t work
    i had to make a whole host of changes

    a) the index.html should be login.php
    b) the variable anme in the PHP scripts should be set to the same not differnt variables on each page

    can someone check it and fix it please

  22. Nice plugin but I have a small problem.

    on my local xampp it works very well.

    but if I uploaded it to my webspace the window.location redirect doesn’t work.

  23. pls explain some workings of simplemodal.js

  24. hello Gabriel,
    Session is not set in the private.php

    Welcome, | Logout

    This is your private page. You can put specific content here.

    Note after Welcome,the username does not appear…
    I`l be kind enough if u reply

    1. The session is set in config.php. This file is included in private.php.

      To fix the username bug just edit line 26 from do-login.php: change $username to $post_email (the username is actually the e-mail address in this case)

      The purpose of the tutorial is to show a working ajax login from inside a modal box. If you want to integrate it on your website, the PHP files from the ZIP package need some changes though. They were added just for demo purpose.

  25. I’m having a hard time making this work with asp pages (pre asp.net). What is the trick to send the form data? I try changing the php page to the asp equivalent using
    request.Form(“password”)
    instead of
    $_POST['password']
    for example, but it’s not working. Any suggestions on where I can look for help on this?

    Thanks! I love your code otherwise – it’s exactly what I’ve been looking for.

  26. I am have a similar example but no login, but does post data in a similar way on a floating modal box.

    I am trying to retrieve json output, it doesn’t seem to work. On Firebug console something like $(‘#someid’).html(data.output); works.

    Any help?

  27. Hello,

    Gabriel great script thanks for sharing.

    Question, How can I go about configuring the PHP array? Right now the email and password are hard coded, which is fine but how do I add more email and passwords to the $config array?

    Thank you,
    v/r
    JShidell

  28. Hi, This is a great script, been searching for something like this for a long time.

    I am looking to add this function on a new website I am developing, however, I have used Jquery Fancybox for the modal window. Is this script compatible with Fancybox?

    Thanks

  29. If you use the latest version of simplemodal you can use a strict dtd instead of the transitional.

    http://www.ericmmartin.com/projects/simplemodal/

  30. Como hago para colgarlo en una web real, que cambios debo hacerle? Porque anda barbaro local en xampp pero lo cuelgo en la web y no pasa del login.

  31. I found this and thought it’s great, thanks.

    I am currently testing it and I think there are a couple of glitches in the examples downloaded with the zip.

    -The php scripts use “isSet” instead of “isset” and breaks for me, had to change it.
    -The cookies are not being set, it fails cheking the post “remember_me”, the index.html is not sending any “remember_me” value. All the cookie use would need further modifications to work, $usr and $hash are never set to compare, but I know it wasn’t the point in the example to learn.
    -All the ‘username’ checks when failed redirect to login.php but there is no login.php there; logout.php too, leading to 404 error should be index.html.
    -In do-login.php username is given the value of variable $username, although $username is never given any value, this leads to failing login everytime.
    -Failing login redirects to login.php

    Hope this helps others that found this not working, happened to me, and correct me if i’m wrong.
    It works perfect in the view demo link though.

  32. Hello,
    Gabriel great script thanks for sharing.
    when i click submit() form, the success alert show, what’s the problem!

    1. That success alert is just a dummy action. It could have been no action set since the data is sent to the PHP page through AJAX. It appears if the script isn’t setup correctly. Make sure you have the right paths to the JavaScript files, and the right ID is set for the link that is clicked (see the tutorial in detail).

  33. if i change table id into any other “id” this modal box not working??

  34. Hi,Gabriel…
    why this is not working in FF 3.5.9 ?

  35. Hi, thanks for such a great script.
    However, i have placed the “Login” link in a php loop that prints few rows from the database, and i want the modal box to appear when i click on link in each row.

    So far, i could not figure out how to achieve multiple modal boxes, but as Zomb said, he has figured it out, it would be great if someone helps me here :)

  36. Yes, i think i have figured it out….
    you need to write another link for opening up the modal box, like:

    <a id="login_link2……
    <a id="login_link3……

    And in the init.js file, you need to add:

    $("#login_link2").click(function(){
    $('#login_form').modal();
    });

    $("#login_link3").click(function(){
    $('#login_form').modal();
    });
    ………

    Hope iam right….

  37. Hi,

    I have implement this. When successfully logged in then not redirect to private.php… It just echo OK… I have not implemented cookie.

    thanks

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)