Ajax login validation system in PHP using jQuery

Last time, I’ve showed you how to check user availability in Ajax using jQuery’s fading effect. But I’ve just shown the example without connecting the database and some people have faced problem with database connecting solution of that problem.In this post, I’ll show you how to use Ajax login system in php using jQuery and some animation as well.

View Demo

In this example, first of all we’ll validate the user login detail from ajax showing the messages with some animation. If authenticated, the user will be redirected to the secure page “secure.php”. If you’ll try to directly access “secure.php”, you can’t do that.

Now let’s look at the code how to do this,

HTML Code

< form method="post" action="" id="login_form" />
  < input name="username" type="text" id="username" value="" maxlength="20" />
  < input name="password" type="password" id="password" value="" maxlength="20" />
  < input name="Submit" type="submit" id="submit" value="Login" />
< /form >

As you can see in html code, we’ve created the form with id “login_form”.

And furthermore, the CSS code is same as the one available in the pervious post of checking user availability in ajax and php.

JavaScript Code for Ajax Login validation system in PHP

First of all we need to use the jQuery library in our code,

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

Now let’s look at the code in javaScript to call ajax and show the animated message with fading effects.

$("#login_form").submit(function()
{
	//remove all the class add the messagebox classes and start fading
	$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
	//check the username exists or not from ajax
	$.post("ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val(),rand:Math.random() } ,function(data)
        {
	  if(data=='yes') //if correct login detail
	  {
		$("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
		{
 		  //add message and change the class of the box and start fading
		  $(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1,
                  function()
		  {
  	  	     //redirect to secure page
		     document.location='secure.php';
		  });
		});
	  }
	  else
	  {
	  	$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
		{
		  //add message and change the class of the box and start fading
		  $(this).html('Your login detail sucks...').addClass('messageboxerror').fadeTo(900,1);
		});
          }
       });
       return false;//not to post the  form physically
});

As you can see above this code is preety much similar to the previous post of checking username availability in ajax and php and you can see the explanation of the above code from that post. But in above code, where the user is validated, he’ll be logged into the “secure.php” using “document.location” in JavaScript.

$("#password").blur(function()
{
	$("#login_form").trigger('submit');
});

Well, as you can see above javaScript’s code, when focus is moved away from the password it also call the for sumit action. Basically whenever you hit tab button in password field, it starts validating the user detail using ajax.

PHP Code for Ajax Login validation system

First of all lets’s look at the code of the “ajax_login.php”.

//get the posted values
$user_name=htmlspecialchars($_POST['user_name'],ENT_QUOTES);
$pass=md5($_POST['password']); 

//now validating the username and password
$sql="SELECT user_name, password FROM tbl_user WHERE user_name='".$user_name."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result); 

//if username exists
if(mysql_num_rows($result)>0)
{
	//compare the password
	if(strcmp($row['password'],$pass)==0)
	{
		echo "yes";
		//now set the session from here if needed
		$_SESSION['u_name']=$user_name;
	}
	else
		echo "no";
}
else
	echo "no"; //Invalid Login

As you can see above, the user login detial is validated from the database. If the user login detail doesn’t exists, it just returns the “no” values and if the user login detial does exists the it just return “yes” values with setting username in session variable.

Finally, let’s look at the code of secure.php

if(empty($_SESSION['u_name']))
  header("Location:index.html");
//if logout then destroy the session and redirect the user
if(isset($_GET['logout']))
{
  session_destroy();
  header("Location:index.html");
}
echo " <a href='secure.php?logout'><b>Logout<b></a> ";
echo " <div align='center'>You Are inside secured Page</a> ";

As you can see above the code of “secure.php” is simpleforward. If the user is not authenticated by session then he’ll be redirected to “index.html”. And there is link for “logout” in this page form where user can destroy the seession.

Download Full Source Code

Implementation Guide:

To implement this code, dump the tbl_user “table” available in the zip file to your database and configure the database connection in “ajax_login.php”.

156 thoughts on “Ajax login validation system in PHP using jQuery

  1. Kasper

    Hey guys,

    If you need a complete login script with remember me and admin feautures try visting:
    http://evolt.org/PHP-Login-System-with-Admin-Features
    Though I recomend you are rather good at php and php classes. But its greatly made and I put this script together with the script from the link and it works like a breeze.
    I also higly recommend to read and understand this.
    Regards

  2. Kasper

    Once again hi,
    Regarding javascript disabled this can actually be solved verry verry easy in making a php switch one case with php validation and error messaging for javascript disabled and one without.

    And for making the form work just type in the action of the file pointing to the php validation without java and then have javascript remove it. This way when javascript is disabled the form still submits and gives error messages.

    Best regards

  3. Kasper

    Hiya
    Regarding timed events you might want to look in this:
    http://jquery.offput.ca/timers/
    Regards

  4. Deepak

    IT’s is good example…

  5. otto

    There is a error message in Safari. When i click on the username field, the browser gives an error and closes.

    someone knows a solution?

  6. Deep Chandra

    Can you please incorporate remember me feauture into this login.

  7. i want to add two columms to the database one called name and the other lastname.

    when user log in i want to show the name and lastname of the user, how can i do that?

    Regards

  8. Hi one a problem.. in my host already eh created the data base with the necessary permissions but I cannot connect ..

    [17-Aug-2009 06:36:33] PHP Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘mydomain_myuser’@’localhost’ (using password: YES) in /home/mydomain/public_html/demo/login_demo/ajax_login.php on line 4

    technically it is the same code without altering, with the exception of the line where I put my user, password and data base to which one talks about.

  9. Tim

    Anyone out there with a similar script for registering new members?

  10. Kasper

    @Tim:

    http://evolt.org/PHP-Login-System-with-Admin-Features
    Is difnately a site I’d recommend you to look and learn from. Though it requires you know how to code in classes but seriously this here is made with it all 😀

    Regards

  11. Hi Roshan:
    I’m back with a problem with this script….

    I’ve loaded all the downloaded files as they were into my webserver.
    Since my login system does not involve a mysql call (it gets done through API), I’ve removed all the code in the ajax_login.php file, except for testing purposes I kept the echo yes line.

    I assumed ANY values entered in the login form would be acceptable that way, however the script still fails to accept the login.
    Any ideas?

    thanks in advance
    Kamy

  12. I have to furher add that there seems to be a bug in the files.
    I’ve reinstalled all the files and used the proper mysql settings with the sql file that’s provided, and it still fails…..

  13. PLEASE IGNORE MY LAST 2 POSTS!

    The problem was totally on my end and the php session settings.

    Really sorry!

  14. thanks..great code….ur code is the only code i found in net for ajax login…which after validation takes to secure page…it will be much better if u can make it look like light box available in jquery….

  15. sir wat to do if want to use it in my project plz help me out

  16. hi
    the code is working fine on my local wamp server! but it is not running in my webserver , when i uploaded in my website…it says ur login details sucks…i just changed my database settings, page layout..everthing is fine and working in my local server but not in webhosting’s server…plz help!! and can u provide me with code where i can enter series of user id and password…to allow multiplle user login???

  17. Thanks Roshan! You’ve got it. I want to show a more “clear code” to any user that right-click on my page and choose “View Source Code” and this should do it. I just didn’t understand why is that code not inside a .js file!

  18. dmid

    Hi, I love this example, and have got it running on my mac under Mamp.
    Just one question though:
    How would I modify it so that each user that logs in is taken to a different secure page?

  19. Thanks. Useful information.

  20. asrar

    great one … but can i use it with JSP rather than php ??

  21. William Pitt

    This is great. But as I understand AJAX is for changing sections of a page without having to resubmit the whole page. So instead of redirecting to secure.php, it could stay in the same index.html but on the top right cornor you could display the login information.. kind of like the information in Amazon. When you are redirecting the page I believe the whole point of AJAX is lost IMHO

  22. Andrei S

    Hi,

    Great tutorial. Except there is a little bug. After I fill the boxes with something and hit submit, i receive the normal error message, but if I focus on password filed than on user name filed, the submit button triggers automatically. Hope you can fix that :)

    Great job.

  23. huihui

    I found your articles is absolutely useful to me. But I wonder how to apply it into codeIgniter code.
    It always stop at checking message box there but without post the username value to user_availability.php page. Any idea of that? Would you mind to show me how to do it? Will be appreciate if someone can help me with that. Thank you very very much.

  24. Shaka

    Can this login code be altered to use a text file to store the username/password instead of a database

  25. edi

    Hello Roshan,
    Thx a lot for this code which would be very helpfull. However, I am unable to run your download code properly. The validation always fails and says that login detail sucks even when I try with the good login and password. Do you know how I can fix it? Thx for your help.

  26. Gagan Shrestha

    hello roshan,
    your code looks great and simple,
    i tried but some problem occured that i am unable to figure out, hope to get help from u
    My probem is that whe i post the user name and password to ajax_login.php every thing woks fine and it also echoes “yes” but the data variable in the statement if(data==”yes”) in the javascript seems to be blank. when l console.log(“data:”+data) the value of the data in firebug i see that
    data: is printed before “yes”
    seems that my callback function is executed before the value passed is taken by the function….
    some help would be appreciated..

  27. Frank

    Nice coding but I found a bug so u can try login thousands times with not your own username.
    If you fill in an username and a password you can try to hack the account. If you only fill the username you can try hundreds of passwords. If you click on the username the errorbox refreshes everytime! Not a good login for evil hackers!

    roshan do you have a solution for this?

  28. Frank

    Forgot the login form:

  29. great work … I resolve my problema with your comment (jquery trim( ));

  30. Kit

    I don’t understand why you took the approach in first checking for the user and grab the row, then compare the password.

    Why didn’t you just include the password in your SELECT query statement?

    $sql=”SELECT user_name, password FROM tbl_user WHERE user_name='”.$user_name.”‘ AND password = ‘.$password.'”;

    This way you don’t need to return unnecessary result set all the time if an invalid password is provided.

  31. MeD

    Hi,
    I will use it ,
    thanks

  32. I don’t know why, but the md5() function isn’t de-encrypting the password when I try this.

    If I change line 34 on ‘ajax_login.php’ to: echo “rejected password =”.$pass;

    And add the following line between lines 21 and 22 of ‘index.html': alert(data);

    I can see that the password is still very, very encoded and therefore fails the test.

    I’m really curious why this is happening, if you have any ideas.

    Thank you.

  33. Yeah, so the only way I can get it to work is if I change line 27 of ‘ajax_login.php’ to:

    if(strcmp($row[‘password’],$_POST[‘password’])==0)

    Is this somehow risking the security of the site?

  34. Lionel

    Great Script!

    Any help to add the Remember Me checkbox will be welcomed 😀

    I tried to add it, but I am unable to even view if the checkbox is checked or not the ajax_login.php.

    It is something stupid but I can’t find why I can’t see if it exist or not….

    Any help will we be welcomed.

    Thanks all and thanks for this great script

  35. sHWETA

    gr8 tutorial.thanx……………….

  36. shweta

    values r not posting on page.there is some problem with input field nmaes.can u plz sort it out

  37. Nishant

    Ur example is superb.. n i m using it in my application.. but for security issue.. i m facing a problem..
    i can see the username n password i send in firebug of firefox…. is there any way throw which i can hide it.. or encrypt it.?

    Thanks
    Nishant

  38. Lars

    I shamelessly stolen this and included it in my application, saved me surely atleast one hour of work. Thanks man!

  39. Mattias Fjellvang

    Ehm, delete this commment BUT… Could you edit my surname away? “Fjellvang”

    Only want it to say Mattias :-).

    Thanks.

  40. Mattias Fjellvang

    Hi. Me again, you can just delete all my comments, i found the problem in some of my PHP code, so had NOTHING to do with your script.

    Thanks anyways for a nice script!

  41. DenW

    Hi,

    I found your script searching for a login method using AJAX and tried it.
    Everything worked perfectly! Thanks for a great script..

    Yesterday however i decided to change jquery.js to an updated version (jquery-1.4.2-min.js).
    After uploading the new jquery, the login script isn’t working anymore. It simply does nothing (as far as i can tell) after i leave the password field.

    Would be great if you could fix this…

    Thanks for a great script!

  42. OK I must be doing something wrong. The only thing I’ve done differently with your code is to put the form inside a div. When the user goes to an index page and clicks on a link, i load with form with a jquery command. Form loads fine. However, it seems as though the doc ready jquery stuff is not loading at all in the div – I even put an alert in right after the document.ready command and the alert does not display. If i continue to fill out the form and press submit, i’m just returned to my index page.

  43. irmanator

    Wow… simple, straight, and accurate!!!
    Thanks.

  44. hI, thanks for your article but I’m having the same problem as a few people. The log in won’t work regardless of what I try. I read the comments and tried the trim but that doesn’t solve it either :(

  45. bah, comment system sucks :(.. i just entered a long reply for martin, but spam protection sum was wrong and now i need to rewrite everything.

    I make it short. check your ajax_login.php should only contain “yes” or “no” – NO other output like or no. And check if you connected to sql database/no php errors.

  46. malaspigar

    Hi,
    I don’t know who did this, but God bless you.
    You just solved a big problem. Thank you!

  47. Peter

    Hi Roshan, Great tutorial I am having one small problem though.

    I would like to insert my own username and password into the table but when I do this using the command,

    INSERT INTO `tbl_user` VALUES (1, ‘username’, ‘password’);

    It goes into the table fine but when I try to use the new username and password to log in it won’t let me through.

    Can you help?

    Thanks mate!

Comments are closed.