Tuesday, June 10, 2008

jQuery AJAX Login

Wanted to use jQuery to display a login form on a site, and use AJAX to do the login. Seemed easy enough. Prerequisites are jQuery, and jqModal. Created an HTML page with a Login link, and a jqModal div that hides the username, password form.


<a class="display-form">Login</a>

<div id="login" class="jqmDialog">
<div class="jqmdMSG">
<form id="login-form"> here is the login form.
hidden in a jqModal div. The css hides the div.
The jQuery javascript handles the show/hide of the
login form.</form>
</div>
</div>

<script src="text/javascript" >
$().ready( function() {
// setup the login form to display,
// hide itself appropriately.
var t = $('#login div.jqmdMSG');
$('#login').jqm({
// a link of class display-form is clicked,
// the login dialog will be displayed
trigger:'a.display-form',
target: t,
overlay: 30,
onHide: function(h) {
h.o.remove(); // remove the overlay
h.w.fadeOut(888); // fade out the dialog
}
});

// setup the login form to work via ajax
$('#login-form').ajaxForm({
url: 'url to post form to',
beforeSubmit: function(formData, jqForm, options) {
// code executed before form
// is submited could possibly
// display a "Please wait ..."
// and hide the login button on the form
return true;
},
success: function(responseText, statusText) {
// code executed if logged in success
},
error: function(responseText, statusText) {
// code executed if things failed
}
});
});
</script>

No comments: