Hi Folks, i am back with another easy to follow and reuse in your project tutorial, today i will demonstrate on how to code a simple jQuery based login mechanism, first in simple words how the logic works after user have pressed the submit button.

How it Works

  1. We will check if the Username, Password fields are empty, if Yes we will show an error.
  2. Fields are not empty, we will call our function and pass Username and Password values.
  3. Our function will execute jQuery’s Ajax method and will POST the data to php page.
  4. PHP will check the values of Username, Password against our Database
  5. If No Record is found, PHP page returns “notFound”.
  6. We will check the php response that was sent to jQuery’s Ajax’s Response object
  7. If the reponse matches “notFound” we will show “User not found” error
  8. Otherwise, if the Username is found, We will redirect the user to any page we like.

ok this was simple explanation on how the whole thing will work. Now lets get our hands dirty with some some code.

Here’s our Basic Markup

<div id="Container">
<div id="LoginWindow">
<div id="LogoM"> <img src="imgs/logo.png" alt="PhotoReview" /></div>
Simple demonstration on How to Login Using jQuery
<ul>
	<li>
<div class="field"> <span class="leftspace">Username:</span>
            <input id="username" class="login-field" name="uname" type="text" /></div></li>
	<li>
<div class="field"> <span class="leftspace">Password:</span>
            <input id="password" class="login-field" name="pass" type="text" /></div></li>
</ul>
<a class="mybtn" href="#"><img id="loginBtn" src="imgs/loginbtn.png" alt="" /> </a></div>
</div>

Our CSS Styles

*
{
	margin: 0px;
	padding: 0px;
}
OL, UL
{
	list-style: none;
}
#Container
{
	width: 100%;
}
#LogoM
{
	padding: 0 20px 20px;
	width: 321px;
	height: 33px;
	margin-left: -6px;
}
#LoginWindow
{
	width: 355px;
	background-color: #FFF;
	clear: both;
	overflow: hidden;
	padding: 15px 5px 15px 10px;
	margin-left: auto;
	margin-right: auto;
	border: 4px solid #EAEAEA;
	border-top: none;
	min-height: 235px;
}
.field
{
	margin: 5px 0 0 15px;
}
#LoginWindow P
{
	width: 594px;
	font: normal normal 12px Tahoma, Geneva, Verdana;
	padding-bottom: 50px;
	margin-left: 15px;
	width: 330px;
}
#login UL
{
	margin-top: 17px;
}
#login LI
{
	margin-top: -6px;
}
.leftspace
{
	margin: 0 10px;
	top: 10px;
	font-family: Tahoma;
	font-size: 12px;
	font-style: normal;
	font-weight: bold;
	letter-spacing: 0.1em;
	color: #0AE;
}
INPUT#username
{
	margin-left: 16px;
}
INPUT#password
{
	margin-left: 16px;
}
.login-field
{
	margin-bottom: 8px;
	margin-top: 2px;
	width: 200px;
	height: 21px;
}
.topspace
{
	margin-top: 17px;
	margin-left: 10px;
}
#errorMsg
{
	position: absolute;
	top: 226px;
	display: none;
}
#errorMsg P
{
	width: 235px;
	margin: 1px 0 0 25px;
	font-size: 9pt;
}
#loginBtn
{
	float: right;
	margin-right: 23px;
	margin-top: 10px;
	border: none !important;
}

and now our jQuery Code to validate if user have entered some data.

$(document).ready(function(){
	$(".mybtn").click(function() {
		$("div#errorMsg").css("display", "block");
		$("div#errorMsg").html("
 
Please wait!
 
");
 
		//Get values
		var txtUserName = $("input#username").val();
		var txtPassword = $("input#password").val();
 
			// check if the fields are empty
			if((txtUserName=="" ) || (txtPassword== "")){
				$("div#errorMsg").css("display", "block");
				$("div#errorMsg").html("
 
Please Enter Username, Password!
 
");
 
					} else {
						//Call the ajax function to check the usernames
						checkUser(txtUserName, txtPassword);
					}
		}); //end of click event

When user clicks the login button

("div#errorMsg").css("display", "block");
		$("div#errorMsg").html("
 
Please wait!
 
");

we set the “display”attribute of our errorMsg div which we are using for showing general messages to “block” and write some html code to display a paragraph with text.

Next we get the values of the username textfield, password textfield and

//Get values
   var txtUserName  = $("input#username").val();
   var txtPassword  = $("input#password").val();

then assign it to txtUserName, txtPassword variables. After that

// check if the fields are empty
if((txtUserName=="" ) || (txtPassword== "")){
	$("div#errorMsg").css("display", "block");
	$("div#errorMsg").html("
 
Please Enter Username, Password!
 
");
		} else {
		//Call the ajax function to check the usernames
		checkUser(txtUserName, txtPassword);
	}

We run if statement to check if the variable are empty i.e user have submitted empty fields, we will check this on the clients end, if the fields are empty we will show them the error message else we will call our checkUser(txtUserName, txtPassword) function and pass username, password to the function. Before we take a look at checkUser() function i would like to take you through our PHP Page so atleast you will know how the data sent is received and sent back.

PHP Connection file

<?php
$hostname_myDBconn = "localhost";
$database_myDBconn = "jquerydb"; //change this
$username_myDBconn = "username"; //change this
$password_myDBconn = "password"; //change this
$myDBconn = mysql_pconnect($hostname_myDBconn, $username_myDBconn, $password_myDBconn) or trigger_error(mysql_error(),E_USER_ERROR); 
mysql_select_db($database_myDBconn) or die(mysql_error());
?>

then our actual PHP logic Page

<?php
/*
 * jQuery login
 * Version: 1.0
 * Author: Tamuir khan
 *
*/
require_once('../Connections/myDBconn.php');
//Get Vars from Login Page
$username = $_POST['sUname'];
$password = $_POST['sPass'];
	// Check database to see if username and the hashed password exist there.
	$query = "SELECT UserID, UserName FROM users
			  WHERE UserName = '$username' AND UserPass = '$password'";
	$result_set = mysql_query($query);
 
	if($row = mysql_fetch_array($result_set)) {
		//Record found, username,password authenticated
		echo $row['UserName'];
		} else {
			echo "notFound";
		}
?>

On this PHP page we will collect the values that was posted by JQuery’s Ajax call, after that, we will test the values against our database, if record is found! [you can do alot of things here on real system like start a session with the UserID/Username that will be useful on other pages] but in our current scenario, we will echo the “Username”, else if no record is found we will echo “notFound“.

Now lets take a look at our main function that will call above PHP code and redirect user.

Our CheckUser() function

function checkUser(txtUserName, txtPassword){
	var dataString = 'sUname=' + txtUserName + '&amp;sPass=' + txtPassword; // constructing our param variable that will be send with ajax call
 
		// Ajax Call to check if the username / password are correct
		$.ajax({
			type: "POST",
			url: "php/checkUser.php",
			data: dataString,
			success: function(response) {
				if (response == "notFound"){
					$("div#errorMsg").css("display", "block");
					$("div#errorMsg").html("
 
Sorry, Username was not found!
 
");
						} else {
							window.location.replace("http://google.com");
						   	}
					 }
			});
	}  //end of checkUser() function
 
 });//end of jQuery code

When the parameters are received we, will construct another parameter variable that will be sent to php page through jQuery’s Ajax Call, once the call has been made we will check the Ajax response object to see what is sent by PHP page, based on the data we received.

If No Username/password is not found in our database we will receive “notFound”, we will show the error respectively else if the username is found we will redirect the user to a different page, in our current scenario we are redirecting the user to http://google.com’s page but you can redirect user to a different page on your website.


There are endless possibilities you can code this exact thing and make it better, Hope this tutorial helped you learn something new.

Until Next time.. Ciao!


Download filedemo-btn

For demo use “john” as username and “mypass” as password without quotes.

Author: Tamuir khan

I am a Designer and Web Developer at Emrialo, I have been in this industry for over 5 years now. Im a Mac Fanatic + i love playing cards.

Tags: ,

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • LinkedIn
  • Netvibes
  • RSS
  • Technorati
  • Twitter
  • Design Float
  • Mixx
  • Reddit
  • StumbleUpon

This entry was posted on Saturday, December 19th, 2009 at 3:54 pm

and is filed under Tutorials .
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

4 Responses Received.

  1. Januta says:

    great sharing.. nice to get your work…

  2. Valuable info. Lucky me I found your site by accident, I bookmarked it.

  3. Keep the good information comming, we need more authors like you!

  4. DP Solutions says:

    good work, thanks for sharing

Trackbacks/Pingbacks

Leave a Reply

  • Keep Yourself Updated

  • Have any interesting information about web design or tech news?
    Share your links.

    Share News

  • Poll

      • What would you like to see more on BootStrap.pk?

        View Results