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

Posted on April 24, 2009, under AJAX, JavaScript 

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
- – - – - – - – - – - – - – - – -

[eps-product id="155308, 372581, 87399, 158711"]

Comment via Facebook

comments

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

  1. I really like the idea behind Modal window and i know how its useful.

    But all Modal Window and other similarity are triggered after CLICK event. I have to click on SPECIFIC ID to get Modal Window shows up.

    What i’m looking for to have simple Modal Window build by jQuery and it get triggered when user select any text from web page (plain text from P or SPAN tag). And when Modal Window open up it has some data or links or some tabs inside that Modal Window each tab has its own data such as forms or links, images, audio, video, ….etc

    I hope i’m clear and explained myself enough. Im still new to jQuery and searching a lot for such solution or close solution to my idea, but i cant.

    I’ll be so grateful of you can guide me or show how and where to start. Or is it really possible to that.

    Thanks a lot
    Ahmed

  2. Hey I love this thing, but I’m having some issues with the declaration in MSIE. It seems that if I use a standard doctype, like just , the jquery modal script breaks. Is there some fix to the jquery function I can apply so I can use normal doctypes with this thing?

  3. Great, great login! After banging my head and searching for days, I can’t seem to figure out why the validation will not carry all the way through and therefore I am being redirected back to the login page. My backend programming is weak, but I have found that it may be an issue w/ the session or cookie….could someone please post the fix for this? Thank you!

  4. I have a problem. After login this is redirect to login.php that doesn’t exists. I saw in the code that is caused because this line in do-login.php:

    $_SESSION['username'] = $username;

    The variable $username has no value.

  5. in archive missing file: login.php

    1. Hi, in this archive: http://www.box.net/shared/5ij68klazs, missing file: login.php
      You can send it to me? otherwise form does not work(((. Thanks in advance!

      mov260891@yandex.ua

  6. There is a problem with the downloadable demo.

    You can fix it by changing the line
    $_SESSION['username'] = $username;

    in do-login.php…. to

    $_SESSION['username'] = $post_email;

    the problem was that $username was not being set, so in private.php all users were redirected back to index.html

  7. Thanks alot for your script. It has really help me. I however have a challenge passing a variable from php to the init.js file. This is just what i want to accomplish

    function go_to_private_page()
    {
    window.location = ‘main.php?test=(a php variable HERE)’;
    }

    Please help me out.

    Regards

  8. Very nice! I’m using modal box with this nice instant ajax login, works fine for me, http://www.devstring.com/jlogin, maybe it would help


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;)

POSTING RULES:

  • The comment must be relevant with the topic of the post.
  • Only comments with real email addresses will get approved. So, emails like 'abc@domain.com' will not be accepted.
  • Do not post the same message in multiple articles through the site.
  • Do not post advertisements, junk mail or pyramid schemes.
  • In case you post a link to another site, please explain briefly where the link goes as a courtesy to other users.
  • Do not post comments such as: "Thank you", "Awesome", "Nice tutorial", "Merci", etc.