ajax login with php

ajaxlogin

Let us check how to create ajax login with php.
Now a days i sow so many sites that are using ajax in login forms.
Here i’m not dealing with any security related think in login. We can discuss those things in some other post.

So let us start creating ajax login with php.
Firstcreate a table where we need to store user information.

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

INSERT INTO `users` (`user_id`, `username`, `password`) VALUES
(1, 'test1', '123');

Next is the html part. Here at on click of the submit button, a javascript function ‘chk_ajax_login_with_php’ is called.
Which will send ajax request to server.


  <script src="jquery.min.js"></script>
<script>
function chk_ajax_login_with_php(){
  var username=document.getElementById("username").value;
  var password=document.getElementById("password").value;

    var params = "username="+username+"&password="+password;
		   var url = "login.php";
				$.ajax({
							   type: 'POST',
							   url: url,
							   dataType: 'html',
							   data: params,
							   beforeSend: function() {
							     document.getElementById("status").innerHTML= 'checking...'  ;
										 },
							   complete: function() {

							   },
							   success: function(html) {

									 document.getElementById("status").innerHTML= html;
									 if(html=="success"){

									   window.location = "test.php"

									 }

							    }
					   });

}
</script>
<link rel="stylesheet" href="style.css">
<body>
<div id='logindiv'>

		<label>Username:</label>
			<input name="username"  id="username" type="text">
		<label>Password:</label>
			<input name="password" id="password" type="password">
			<input value="Submit" name="submit" class="submit" type="submit" onclick='chk_ajax_login_with_php();'>
        <div id='status'></div>
</div>

Next is the php part. here we will check the user name and password. if information is correct we will set a session and sent a success message.
If information is incorrect we will sent a failure message.


 include "dbconnect.php";
  if($_POST){

	  $username=$_POST['username'];
	  $password=$_POST['password'];

	   $sql=mysql_query("select * from users where username='$username' and password='$password'");
	   $res=mysql_num_rows($sql);

	   if($res>0){

	      $rs_login=mysql_fetch_assoc($sql);
		  $uid=$rs_login['user_id'];
		  $_SESSION['sess_uid']=$uid;
		  echo "success";

	   }else{

		 echo "invalid username or password";

	   }
   }

So like this you can easily create an ajax login with php
Download               Labs