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

36 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
  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. This comment has been removed by the author.

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

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

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

    php mysqli login form

    ReplyDelete
  21. "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
  22. Thanks for sharing with us that awesome article you have amazing blog.

    Best Linux training in Noida
    Linux Training Institute in Noida

    ReplyDelete
  23. nice post very full keep it up,
    simple laravel login registration ,
    https://www.tutsmake.com/laravel-login-authentication/

    ReplyDelete
  24. wonderful post.it will help lot of student to improve there skill.
    for Web design and php classes plz do visit this site
    Web design training institute in Nagpur

    ReplyDelete
  25. Superb blog I visit this blog it's extremely marvelous. Interestingly, in this blog content composed plainly and justifiable. The substance of data is exceptionally instructive.
    oracle fusion financials classroom training
    Workday HCM Online Training
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training
    Oracle Fusion HCM Classroom Training

    ReplyDelete
  26. How To Insert Password And Confirm Password Using Ajax In Laravel

    Using Ajax is another way to insert Passsword with Json request in Laravel. Here you can see, we are using controller, model and send response to ajax via Json..

    For More Info:- How To Insert Password And Confirm Password Using Ajax In Laravel

    ReplyDelete