Login Form Using Ajax and jQuery

Login Form Using Ajax and jQuery

In my post labeled under ajax category you learned how to make user poll script using ajax and php. In this post we'll be creating an ajax login form using jquery and php.

This post contains four simple steps which are as below.

First of all we are creating database that contains the data of the registered users. To create the database just copy and paste the code given below in the step:1

Step:1 Create table - registered_users

CREATE TABLE IF NOT EXISTS `registered_users`(
`name` varchar(20) NOT NULL,
`password` varchar(50) NOT NULL,

Now we have database of the users. Its time to create a login form through which user can login. Create file named index.php and copy paste the code of step:2.

Step:2 Create file - index.php

In index.php file we'll have the small login form through which user can enter Username and Password. Entered data will be checked against the correct credentials for the login if they are correct then user will be redirected to the next page.

Note: Here this file has little more code. So i can't write down here. You can download the full source from the given Links.

In the login form we are getting the values entered by the users and sending these data using ajax request and checking them against the credentials. Following file named login.php will perform the same checking and return the response based on the requested data.

Tip: This example is just to clear the basic concept, for the security concerns you can use the Prepared Statements. Using prepared statements will help protect you from SQL injection.

You can use the FluentPDO - smart SQL builder for PHP.

Step:3 Create file - login.php


$username = $_POST['name'];
$password = md5($_POST['pwd']);
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_password = "";
$mysql_db_database = "test";
$con = mysql_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password)
or die("Could not connect database");
mysql_select_db($mysql_db_database, $con)or die("Could not select database");

$query = "SELECT * FROM registered_users WHERE name='$username' AND password='$password'";
$result = mysql_query($query)or die(mysql_error());
$num_row = mysql_num_rows($result);
if( $num_row >=1 ) { 
echo 'true';
echo 'false';

After successfull login,user will be redirected to the given page url.Now when user clicks on the logout button session will be destroyed and user redirected to the main page.

Step:4 Create file - logout.php

 header('Location: index.php');

Thats it..! Your Ajax Login form with jquery and PHP is Completed.If you have any question or query then please comment.

Download Source