How to create an ajax login form using jquery and php

In this tutorial, I’m going to show you how to create an ajax-powered login form. Using jquery and php.
Ajax means Asynchronous Javascript And XML. People in the web-design industry often make use of it to load data from the server without refreshing the page. But don’t take my word for it, there are many other usage for ajax. I’m just here to show you an application.

And to get you excited here’s a sample output.

image

And yeah, there’s really nothing exciting about my css skills. I just suck at css. So I’ll just leave the styling as your homework.

Requirements

  • jquery core
  • wampserver – or anything which includes php, a database, and a server

Assumptions

I assume that you already know the basics of jquery and php. And how to use ajax:

Dynamically load mysql data using jQuery and PHP


Procedure

First, you have to prepare all the files needed and place them on a single folder. That folder will be your work folder.

Next, create a file which will contain the form that you just saw above. Name it whatever you like to name it.

Okay, so here’s the basic css which aligns the labels and text fields, and images so that it won’t look messy.

<style type="text/css">
form {
  margin: 0;
  padding: 0;
  font-size: 100%;
  min-width: 460px;
  max-width: 620px;
  width: 190px;
}
label {
  display: block;
  float: left;
  width: 130px;
  padding: 3px 5px;
  margin: 0 0 5px 0;
  text-align: right;
}

.txt{
  margin: 0 0 0 15px;
  width:230px;
} 

.btn{
  margin-left:334px;
}
</style>

Then include the jquery file on your page.

After that, go ahead and build the form:

<form name="frm_bpls_login">
<fieldset id="fs_bpls_login">
<legend id="leg_bpls_login">User login</legend>
<p>
<div id="id_stat">
<label for="user_id">User ID:</label>
<input type="text" name="user_id" id="user_id" class="txt"/>
<img src="img/chk_on.png" id="img_id"/>
</div>
</p>
<p>
<div id="user_stat">
<label for="password">Password:</label>
<input type="password" name="pword" id="pword" class="txt"/>
<img src="img/chk_on.png" id="img_pword"/>
</div>
</p>
<p>
<input type="submit" name="btn_login" id="btn_login" value="login" class="btn"/>
</p>
</fieldset>
</form>

This is just a basic markup, wherein we make use of a paragraph tag as a line break. Then a div tag to group the label, the text field, and the image together.

As you can see, I’ve already put a default image. But we will hide it from the user using jquery, so that they will only start appearing after the user has pressed tab on the keyboard.

Go ahead, and point your mouse cursor to the head portion of your markup. And start typing the script tag, and the document.ready() function. After doing that, declare two variables which will store the value of the user id and the password inputted by the user. Also declare a rule which will hide all the image in the page. You will have to tweak this code if you have other images on your page which you want to show up immediately after the page has loaded.

var usrid = '';
var pword = '';
$('img').hide();

Next, create a blur() function for the user_id text field, and the password field. You can also use the keyup() function. But that would be overkill, and not really resource friendly, since you will be performing a query every time you type something on your keyboard as long as you are on that specific text field.

$('#user_id').blur(function(){

});

$('#pword').blur(function(){

});

And now, for the code that we will put inside the user_id blur() function. You have to first assign the value of the user_id text field to the user id variable which we declared earlier.

usrid = $(this).val();

Then perform an ajax call:

$.ajax({
   type: "POST",
   url: "php/ajax/user_validation.php?aa=val_id",
   data: "usrid=" + usrid ,
   success: function(data){
       if(data == 1){
	$('#img_id').attr('src','img/chk_on.png');
	$('#img_id').show();
       }else{
	$('#img_id').attr('src','img/chk_off.png');
	$('#img_id').show();
	}
}
});

So what’s with all that code? Here’s my explanation. First we call up the ajax function which is built-in to jquery. Then we specified the type of request to be POST. If you still remember your web design/ web development or whatever subject is that. There are 2 types of request:

  • POST
  • GET

POST is basically hidden,has no limit, and more secure compared to GET.
On the other hand, GET makes use of the URL to pass variables or data from one page to another. Basically, what were doing is emulating the process by means of javascript (jquery is a javascript library).

Next is the url. Here we specify the exact location of the php script in which we want to submit the data. In this case, it is user_validation.php which we will write in a few moments. You might also noticed that we also submitted a GET variable ‘aa’ and then assigned ‘val_id’. In the php script which we will be creating later, there is a switch statement. In programming we use it to come up with different outcomes depending on the input. The ‘val_id’ that we assigned means that we are going to validate the user id. If this is all unclear, you’ll understand later once we build the php script.

Next is the data. This is where we specify the variables which we will pass to the php script using the POST method. In this case, the user id.

Then success is the action which you want to perform after the data has been successfully sent to the target script which is the user_validation.php. In the php script which we will build later, we output the value of 1 if there is a match to the user ID, and then 0 if there is non. That value is being assigned to the data variable in jquery, and that is what we are checking. If the value is 1, obviously we want the user to see a checkmark and if it is 0 we show them the cross mark.

After all that explanation, I guess you’ll be fine in writing the code for the validation of password. If not, then you can go check out the files section of this blog and see if the files that I used for this tutorial is already available.

And now, for the php script that I have been talking about this whole time.

$val = $_GET['aa'];
switch($val){
case 'val_id':
	$user_id = $_POST['usrid'];
	$select_usrid = $db->query("SELECT UserID FROM sys_users WHERE BINARY UserID='$user_id'");

	if($select_usrid  == 1){
		echo 1;
	}else{
		echo 0;
		}
	break;
}

That is what is written in user_validation.php. First we assigned the value of the GET variable ‘aa’ to $val. Then we performed a switch statement. If the value of ‘aa’ is ‘val_id’. We validate the user id by performing a query in the database. And yup, the ‘WHERE BINARY’ is not an ordinary sight. Because it is used to select the exact string.

Here’s an example to help you understand:

  • Often times we do something like this to select a single field on our table:
SELECT UserID FROM sys_users WHERE  UserID='$user_id'

But if you are a good observer, you might have noticed that the query will still return a result if the query string is ‘DOG’, and what is in the database is ‘dog’. UPPERCASE is not the same as lowercase.

But if you use the BINARY keyword:

SELECT UserID FROM sys_users WHERE BINARY UserID='$user_id'

You won’t get any results if your query string is not perfectly the same with the one in the table. This is useful when selecting fields which has unique data on it. Passwords and user id’s are some of the examples.

Conclusion

So I guess that’s it for this tutorial. You have just learned how to create an ajax login form. You might be asking how is useful. Good question! I believe that using this method will save a lot of effort in the part of the user. Because the user won’t have to wait for the server response to know that his login credentials are correct. The user is assured that his credentials are correct before clicking on the LOGIN button. This might put more load to the database server especially if there are more than a thousand records. But its still worth it.

One thought on “How to create an ajax login form using jquery and php

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s