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. @manpreet- you can use the following PHP code to check weather the user is logged in or not

    if(empty($_SESSION[‘u_name’]))
    header(“Location:index.html”);

  2. manpreet

    hi roshan when i am including this code in starting of every page
    if(empty($_SESSION[‘u_name’])){
    header(“Location:index.html”);
    $ff = 1;
    }
    if(isset($_GET[‘logout’]))
    {echo $_GET[‘logout’];
    session_destroy();
    header(“Location:index.html”);}
    then without login i cant enter to any page its sending back to index.html. but after lgin its working fine. wht i do so it can check properly.

  3. Ian

    Hi Roshan,
    Is there are way i can add a “remember me” feature along with this? I attempted to add it to $.post but it just keeps on thinking the remember me radio button is ticked when it is not. How can i make it check if its ticked or not?
    Thank You SO Much for this wonderful script.

  4. @Ian- you can use cookie for adding remember me script….

  5. Ian

    @Ian- you can use cookie for adding remember me script….
    But how do i set the cookie?
    Because its ajax_login.php that sets the session, so i should be using it to set the cookie.
    I used …
    if($remember == “1”){
    setcookie(“mPanelID”, $_SESSION[‘u_name’], time()+60*60*24*100, “/”);
    }
    $remember being $_POST[remember]
    but it doesnt work!
    Must i add remember:$(‘#remember’).val(), or something like that?

  6. Lukas

    Hi!

    Nice script there. I’m trying to use it in another Layout but I’m facing one problem:

    The POST-Data is posted (according to FireBug) but when I print $_POST in ajax_login.php it’s empty! Therefore login always fails.

    Any idea to that. Help is much appreciated!!!

    THX in forward!

  7. @Lukas…if the value is being posted but it’s not coming to the PHP page then there must be problem with the file name or path..please check the path once again..

  8. Lukas

    @roshan
    Thanks for the fast reply!

    In the case you mention, the PHP Page wouldn’t answer right? But it does! Also FireBug would tell me. Any other idea?

    Many thanks!

  9. POGRAN

    Hm.. Nice one, but don’t you think its dangerous to pass url of .php file in JavaScript so that everyone can see it from source? I’m talking about ajax_login.php ??

  10. @pogran- As you know javascript code is visible with browser and in every ajax application you must pass the file name containing server side scripting so it doesn’t matter to pass the .php file name but you must account the security matter in that PHP file……

  11. POGRAN

    Yes, that’s right. JavaScript is what it is, but I meant dangerousness of using Ajax for login in general, not your solution..
    For example if you use regular server-side method, you maybe won’t get so nice effect but so you don’t show file names to others.
    In your script transaction of password to ajax_login.php is also not so perfect. Php file tells if it gets correct password for known username, all is needed for it is to create simple html page with correct input names and send with POST method..
    Well, truly to say, I don’t see any progress of this but still I think its reasonable to add some more params by sending them to php file so that it would be harder to use it ‘from outside’!

  12. @POGRAN – hello dude…..it’s not a professional solution and blog tutorial like only shows how to do the particular task simply and easily… it’s the part of users who have to add the security upto which extent do they need it.

    Now another user may comment that it needs Captcha in the login form. It’s all your job dude to add the additional security.

    And the method you’re talking about sending data via POST method is also not secure as it can be intruded with CSRF request.

  13. David

    Hi,
    regarding Ian’s reply, is there anyway to add a ‘Remember Me’ Checkbox and feature to this login so that it the javascript checks if its ticked and posts it and if its not tick it wont post it. I know how to do the cookies and all, its the java side im having problems with, please help! thanks

  14. @David- you can use two functions of javascript set and get the values from cookie of the link below.

    http://www.w3schools.com/JS/js_cookies.asp

  15. Hi Roshan! thanks for your great application. I am using this in conjunction with thickbox to make some really great forms on my website. One major problem I am having though, is passing a tag through the ajax.
    i have:

    Apple
    Microsoft
    Sony
    Nintendo

    have defined nptg:$(‘#nptg’).val()

    but in my ajax.php file, $_POST[‘nptg’] returns undefined

    any quick fixes? Again, thanks for the AWESOME work!

  16. sorry! the comment system seems to eliminate my html.
    i am using a select, drop down form element.

    its name=nptg, and options are apple microsoft sony and nintendo.

  17. Figured it out, in your select element you need an id=

  18. Eusebio

    Congratulations, a great script.
    Please, two questions:

    1 -How makes two checks on the same page?

    $(document).ready(function() {
    $(“#code”).blur(function()
    });// end 1

    $(document).ready(function() {
    $(“#city”).blur(function()
    });// end 2

    2 – How to use two blur in the same check?

    $(document).ready(function() {
    $(“#city”).blur(function(); $(“#state”).blur(function()
    });

    Please help! thanks, Eusebio

  19. @Eusebio – use this wasy
    $(”#city #code”).blur(function()

    and

    $(”#city #state”).blur(function();

  20. Eusebio

    thanks… but it did not work

    They are two different situations ..

    First:
    When there is any change in the two fields, only make a check.
    //if the city is compatible with the state
    $(”#city”).blur(function(); $(”#state”).blur(function()
    $.post(“check_city_state.php

    Second:
    Two different checks to different fields, on the same page.
    //if the NICK exist ??
    $(document).ready(function() {
    $(”#nick”).blur(function()
    $.post(“check_nick.php

    //if the EMAIL exist ??
    $(document).ready(function() {
    $(”#email”).blur(function()
    $.post(“check_email.php

    Sorry my english
    thanks

  21. this is really magnificent to login via ajax without reloading the page i like it

  22. Janne

    Hi Roshan

    Your pages r cool. I have tested your nice login system little bit and i trying to get it work with thickbox. Login system working nicelly when i try it outside of thicbox, but when i opening login form to thickbox, then some reason i do not get return value of $.post() function. Or at least i look to be like that. Do you have any idea what i should try to get over this issue?

  23. @Janne – which thickbox you’re using ? can you show me the link of thickbox u’re using ?

  24. wako

    when i type the username and password it always says that your login detail sucks..
    how can i fix it?
    i dont know if my database connects… pls teach me how coz i’m a beginer in php and i want to learn because of my god damn thesis… pls help me mr. roshan…..
    thanks a lot.. i hope you could help me….

    ty.

  25. Great post. I was struggling for a while trying to get it to work in my app but finally figured it out. I was encoding the file ajax_login.php with UTF-8 with BOM when I encoded in UTF-8 without BOM it worked

  26. veasna_set

    Hi Roshan,
    I really like your code. Furthermore, If log in fail, i want to show message for a while only (5 seconds) then disappear message. What should i do with it?
    Thanks in advanced.

  27. agus

    Hi. Roshan, it is small great article…
    I wondered to put the login form script in index.html into ajax_login.php
    using this condition, if(data==’yes’) . it is doesn’t work. why? thank’s in advance

  28. Jesper

    Great tutorial! But why the rand:Math.random() parameter?

  29. Aman

    Hi,

    Great tutorial. I was wondering wthat the purpose of “math.random” is in this line:

    $.post(“ajax_login.php”,{ user_name:$(‘#username’).val(),password:$(‘#password’).val(),rand:Math.random() } ,function(data)
    {

    Thanks,
    Aman

  30. John

    Hi Roshan ,

    Can you help me out ,using check user availablity in Ruby on Rails Apps .
    Thanks in advance

  31. Rafa Muñoz

    Hi Rosham. Thanks for this excellent login system.
    Unfortunatelly I can’t use it. If I put all files in my main localhost folder, it runs good, but if I move them to another directory, it doesn’t work.
    It’s not problem about check permissions or the DB. I’ve tried to change this:
    $.post(“ajax_login.php”
    to this:
    $.post(“admin/test/ajax_login.php”

    but still doesn’t work.

    Thanks for your help.

  32. you don’t say exactly how to replace the password in the original zip.

    If I wanted to have “user” as user name and “mypass” as the password, HOW CAN I DO IT?

    I’ve tried everything: changing in the provided sql does not work, i’ve even tried to replace the $pass variable with a lame string ‘mypass’…it doesn’t work….nice tutorial, but incomplete 😐

  33. svs

    Hi,
    Nice code,put remember me and forgot password option also.

  34. hey, great work here mate.
    Got a little problem tho. Im calling the app in a Fancybox and I cant see the errors inside it, seems like it will not validate before sending so to speak.

  35. Simon

    Hi Roshan,

    I tried to view your demo and in case you don’t already know Google listed your site as suspicious.
    Line from Google report:
    Malicious software includes 62 exploit(s), 54 scripting exploit(s), 15 trojan(s). Successful infection resulted in an average of 36 new processes on the target machine.
    I hope it’s nothing serious.

    Simon

  36. Anderson

    Hello Roshan
    First I want to congratulate you for you blog.
    Now my question: I’m doing a project where security is a BIG concern and when I try to see your demo I receive a page that tells me it’s dangerous and give this explanation:

    http://safebrowsing.clients.google.com/safebrowsing/diagnostic?client=Firefox&hl=en-EN&site=http://roshanbh.com.np/examples/ajax-login-php

    Is it true? If it’s true, how can this happen? Is this code vulnerable to code injection or what?

    Thanks,
    Anderson

  37. hi anderson…….I had some problem with malware…now everything is alright…you can see the all of them again without any problem.

  38. for preventing the response being cached. You can also use jquery’s ajax method and set the cache to false.

  39. Mike

    Nevermind! I figured it out! I had been echoing some debug info in my db-connection file and it was returning the debug info instead of YES. hahaha.

  40. Peter

    How can i do if i want to redirect to page with username?
    document.location=’user.php?user=username';

    please help me out

  41. Zheng Ji'an

    Thank you Roshan! The script works like charm!

  42. Daniel

    Work good, thanks…

  43. Julian

    Nevermind I fiqured it out, just had it redirect to my old login.php and used the session as the memid.
    session_start();
    session_register(‘frontuser’);
    require_once(“config.php”);
    require_once(“functions.php”);

    $upmemid=$_SESSION[‘frontuser’];
    if(isset($_GET[‘SQL2′]))
    {
    $memid=str_replace(“‘”,”””,$_GET[‘SQL2′]);
    $namestr=fetchMember ($memid);
    $namestr=split(“#”,$namestr);
    $curbalance=$namestr[2];
    }

  44. Alkin

    I have a problem. When i input name nad password, the form submit when i click on page or if i clock on remember mi checkbox. Is it possible to submit the form only if i click submit button. Thank you for this great script.

  45. First of all thanks a million for the script!!!!!!

    Second please let me know how can i remove the message box after some time interval?

    Thanks again and keep it up as we need them (the scripts offcourse) 😉 :)!!!!!!!!!

  46. LGB

    How can i change the password and can i add more than one user?

  47. Anand Chhetri

    development
    testing
     

    After validation I would like to redirect the page to development.html or testing.html based on the value of the selected radio button instead of secure.php
    I can’t get the value of the radio button..any help?????

  48. Hello Roshan,
    I liked your work. But I don’t know where to place the username and password. Can I add more username and passwords for more members. Please help.

  49. cool 😉

  50. ??

    great work, really appreciate for sharing your thoughts and ideas,

Comments are closed.