Pages

Ajax Login form with jQuery and PHP

Tuesday, May 15, 2012
In this tutorial, I will explain you how to create a ajax popup log in form with jquery and php.
Demo
Firstly let's create a folder in your www (for wamp) folder and name as ajax_login.

Crate a blank document in your favourite editor and paste following code in your document. And then save as index.php in your ajax_login folder. I have divided index.php into 2 parts. Below is our body part.

<body>
 <?php session_start(); ?>
 <div id="profile">
  <?php if(isset($_SESSION['user_name'])){
  ?>
   <a href='logout.php' id='logout'>Logout</a>
  <?php }else {?>
   <a id="login_a" href="#">login</a>
  <?php } ?>
 </div>
 <div id="login_form">
 <div class="err" id="add_err"></div>
 <form action="login.php">
  <label>User Name:</label>
  <input type="text" id="user_name" name="user_name" />
  <label>Password:</label>
  <input type="password" id="password" name="password" />
  <label></label><br/>
  <input type="submit" id="login" value="Login" />
  <input type="button" id="cancel_hide" value="Cancel" />
 </form>
 </div>
 <div id="shadow" class="popup"></div>
</body>

In this part, we use the php session variable to check whether the user have already logged in or not. To use session, you need to add session_start() function firstly. If the user has already logged in, we will show the logout. Else we will show login.

And then I create our login_form. We don't want to show this form before the user click the login link. So we need to add the css display:none to our css file for our login_form div.

Following code is our css file. So crate a blank document in your favourite editor and paste the following code. And then save as styles.css in our project folder.

.popup
{
   position: fixed;
   width: 100%;
   opacity: 0.9;
   top:0px;
   min-height:200px;
   height:100%;
   z-index: 100;
   background: #FFFFFF;
   font-size: 20px;
   text-align: center;
   display:none;
}
#login_form
{
 position:absolute;
 width:200px;
 top:100px;
 left:45%;
 background-color:#DDD;
 padding:10px;
 border:1px solid #AAA;
 display:none;
 z-index:101;
 -moz-border-radius: 10px;
 -moz-box-shadow: 0 0 10px #aaa;
 -webkit-border-radius: 10px;
 -webkit-box-shadow: 0 0 10px #aaa;
}

In the index.php head part, first attach the jQuery Library file. And you also need to attach our styles.css. Then write AJAX code into <head> section as following procedure:

<script type="text/javascript">
$(document).ready(function(){
 $("#login_a").click(function(){
  $("#shadow").fadeIn("normal");
  $("#login_form").fadeIn("normal");
  $("#user_name").focus();
 });
 $("#cancel_hide").click(function(){
  $("#login_form").fadeOut("normal");
  $("#shadow").fadeOut();
 });
 $("#login").click(function(){

  username=$("#user_name").val();
  password=$("#password").val();
  $.ajax({
   type: "POST",
   url: "login.php",
   data: "name="+username+"&pwd="+password,
   success: function(html){
    if(html=='true')
    {
     $("#login_form").fadeOut("normal");
     $("#shadow").fadeOut();
     $("#profile").html("<a href='logout.php' id='logout'>Logout</a>");

    }
    else
    {
     $("#add_err").html("Wrong username or password");
    }
   },
   beforeSend:function()
   {
    $("#add_err").html("Loading...")
   }
  });
  return false;
 });
});
</script>

Now let's create a login.php script.

<?php
 session_start();
 $username = $_POST['name'];
 $password = md5($_POST['pwd']);
 $mysqli=mysqli_connect('localhost','username','password','database');
 $query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
 $result = mysqli_query($mysqli,$query)or die(mysqli_error());
 $num_row = mysqli_num_rows($result);
 $row=mysqli_fetch_array($result);
 if( $num_row >=1 ) {
  echo 'true';
  $_SESSION['user_name']=$row['username'];
 }
 else{
 echo 'false';
 }
?>

They are fairly straightforward to understand if you know about php and mysql. But you need to change username, password, database and table name for mysql. If you have a problem, don't hesitate to ask me.
The last thing we need to create is logout.php.

<?php
 session_start();
 unset($_SESSION['user_name']);
 header('Location: index.php');
?>

I think this tutorial will help you.

Download Source Code

34 comments:

  1. I always get this message: Wrong username and password... :/

    I've already change the values(username..etc)

    ReplyDelete
    Replies
    1. try this
      $query = "SELECT * FROM user WHERE username='".$username."' AND password='".$password."'";

      Delete
    2. also change this

      $row=mysql_fetch_array($result);
      to
      $row=mysql_fetch_assoc($result);

      i'm using mysql and not mysqli.

      Delete
  2. I also have the same problem "Wrong username and password", then I tried to run "login.php" only and I got this error
    "
    Notice: Undefined index: name in C:\xampp\htdocs\ajax_login\login.php on line 3

    Notice: Undefined index: pwd in C:\xampp\htdocs\ajax_login\login.php on line 4
    "
    appreciate your help

    ReplyDelete
  3. @ephraym aguila

    could you show us your code to find what went wrong.
    i've used this method and its working.

    ReplyDelete
  4. somebody send mi login for coding

    (create login form without refreshing login shutdown process)

    send mi this code
    chetangharat74@gmail.com

    ReplyDelete
    Replies
    1. Thank you so much for this amazing posts and please keep update like this excellent article. thank you for sharing such a great blog with us.
      seo classes in nagpur
      web design training institute in nagpur

      Delete
  5. For those who are having issues, replace your login.php with this:

    MySQLi version:
    <?php
    session_start();
    $mysqli = mysqli_connect('localhost', 'username', 'password', 'database') or exit('Couldn\'t connect');
    $_POST['name'] = isset($_POST['name']) && is_string($_POST['name']) ? mysqli_real_escape_string($mysqli, $_POST['name']) : null;
    $_POST['pwd'] = isset($_POST['pwd']) && is_string($_POST['pwd']) ? mysqli_real_escape_string($mysqli, $_POST['pwd']) : null;
    $result = mysqli_query($mysqli, sprintf("SELECT `username` FROM `user` WHERE ((`username` = '%s') AND (`password` = '%s'))", $_POST['name'], $_POST['pwd'])) or exit(mysqli_error());
    if(!mysqli_num_rows($result))
    echo "Incorrect login details entered";
    else {
    $row = mysqli_fetch_assoc($result);
    $_SESSION['user_name'] = $row['username'];
    echo "Access granted";
    }
    ?>

    MySQL version:
    <?php
    session_start();
    $mysql = mysql_connect('localhost', 'username', 'password') or exit('Couldn\'t connect');
    mysql_select_db('database', $mysql) or exit('Invalid database');
    $_POST['name'] = isset($_POST['name']) && is_string($_POST['name']) ? mysql_real_escape_string($_POST['name'], $mysql) : null;
    $_POST['pwd'] = isset($_POST['pwd']) && is_string($_POST['pwd']) ? mysql_real_escape_string($_POST['pwd'], $mysql) : null;
    $result = mysql_query(sprintf("SELECT `username` FROM `user` WHERE ((`username` = '%s') AND (`password` = '%s'))", $_POST['name'], $_POST['pwd']), $mysql) or exit(mysql_error());
    if(!mysql_num_rows($result))
    echo "Incorrect login details entered";
    else {
    $row = mysql_fetch_assoc($result);
    $_SESSION['user_name'] = $row['username'];
    echo "Access granted";
    }
    ?>

    ReplyDelete
    Replies
    1. I tried still the same error. I think the login.php is not the problem maybe its in the index.php.
      Not sure though.

      Delete
  6. can you check the ajax script please! maybe the problem is in that part. Thanks!

    ReplyDelete
  7. you have to remove md5 ..
    at $password = md5($_POST['pwd']);

    ReplyDelete
  8. the problem is with AJAX part. Somehow if (html == 'true') is not working even when you just simply echo true in login file.

    ReplyDelete
    Replies
    1. echoing an integer seems to solve the problem. I have no idea why yet.

      change echo 'true'; to echo 1 in login.php
      and if(html=='true') to if(html==1') in the javascript file.

      Delete
  9. $username = $_POST['name'];
    $password = $_POST['pwd'];

    use this on login page remove md5 from password

    ReplyDelete
  10. How to call different page in the pop up??

    ReplyDelete
  11. I want to connect with sql server database with popup login can u send me the code
    This is my E-mail id Plzzz send me the code
    mishraashok5@gmail.com

    ReplyDelete
  12. Please check http://devbro.in it may help you

    ReplyDelete
  13. I add it in http://www.ideaschile.cl/form_login.php Thanks!

    ReplyDelete
  14. For all the people that had the problem about "Wrong username or password" ... remove MD5 at $password in the login.php file ....

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. What is the default username and password that can access and log in it
    Where and how can i add the username and password ?

    ReplyDelete
  17. Nice blog...Very useful information is providing by ur blog. Great beginning php tutorials Very clear and helpful for beginners.

    ReplyDelete
  18. Good efforts. All the best for future posts. I have bookmarked you. Well done. I read and like this post. Thanks. graphic designing courses in jalandhar

    ReplyDelete
  19. Awesome post!!! Thanks for sharing information about PHP courses and PHP classes. This blog post looking interesting. Very useful information. Good going.

    ReplyDelete
  20. informative... above queries should post their errors too...

    ReplyDelete
  21. Today I watched pirates of the caribbean I'think it was forty third time.

    php mysqli login form

    ReplyDelete
  22. "Nice and good article.. it is very useful for me to learn and understand easily.. thanks for sharing your valuable information and time.. please keep updating.php jobs in hyderabad.
    "

    ReplyDelete
  23. Thanks for sharing with us that awesome article you have amazing blog.

    Best Linux training in Noida
    Linux Training Institute in Noida

    ReplyDelete