Today’s tutorial focusing on a very Important stuff that is really needed for both the Beginner and Intermediate web developers. Yes, this tutorial is about creating a effective jQuery Login and Signup form with PHP.
If you want to see the DEMO or DOWNLOAD the script. Please scroll down to the bottom of this post!!
So, what all functionalities are there in this jQuery Ajax Login form?
1. It has both the Login form and Signup form together!
2. Both works without refreshing the page with the help of jQuery ajax POST function.
3. While Signing up checks if the Email is already registered or not.
4. Can be able to log in immediately after a successful registration without refresh!
5. A hidden page will be able to access only after a valid login.
6. Logout option.
How many files are there in this script?
There are four files:
1. index.php – this has the login form and registration form.
2. hiddenpage.php – this file can be accessed only after logged in (PHP Session).
3. checklogin.php – this file checks if the entered username and password is already there in the database or not.
4. check-email-registered – this file checks if the email id is already registered.
5. adduser.php – which is obviously adds the new user in the database.
6. db_con.php – it has the DB connections and database.
You need to create a database and table for this script or you can use an existing database but you should create a table to test this.
Here is the SQL for the table ‘user_table‘:
CREATE TABLE IF NOT EXISTS `user_table` ( `id` int(5) NOT NULL AUTO_INCREMENT, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `user_table` -- INSERT INTO `user_table` (`id`, `email`, `password`) VALUES (1, 'test@test.com', 'ae2b1fca515949e5d54fb22b8ed95575'), (2, 'spider@spider.com', '4620cc8252ffe1ce9ba795cb341eff75');
Let’s see the HTML part of the first file, index.php
<div id="options"> <input type="radio" name="login_option" id="show_login" checked="checked"/> Existing User! <input type="radio" name="login_option" id="show_signup"/>New User!<br /> </div> <div id="login_form"> <h3>Login with your email and password</h3> <label>Email</label><input type="text" name="email" id="email"/><br /> <label>Password</label><input type="password" name="password" id="password"/><br/> <div class="msg"> </div> <button id="login">Login</button> </div> <div id="signup_form" style="display:none"> <h3>Registration Form</h3> <label>Enter Email</label><input type="text" name="email-new" id="email-new" class="chkifalready"/><span class="email_err"></span><br /> <label>Create Password</label><input type="password" name="password-new" id="password-new"/><br/> <div class="msg"> </div> <button id="signup">Signup</button> </div>
If you see the above code, there are two forms wrapped by two DIVs, by default the second DIV “signup_form” is hidden (display:none).
So, once the page loads you will able to see only the “login_form“, but this can be togged with two radio buttons where you can see the very first div “options“, with the help of jQuery on selecting the first radio button will show the “login_form” and by select the second radio button will the “signup_form“.
jQuery part for the above functionality is here:
//toggle forms $('#show_login').click(function(){ $('#login_form').show(); $('#signup_form').hide(); $('.msg').html(''); }); $('#show_signup').click(function(){ $('#login_form').hide(); $('#signup_form').show(); $('.msg').html(''); });
Now the next part is “Login Form jQuery Part” which is again in index.php:
$('#login').click(function(){ //get the values var email = $('#email').val(); var password = $('#password').val(); if(!validateEmail(email)){ $('.msg').text('Invalid email'); return; } //validate the form if(email == '' || password == ''){ $('.msg').text('Please fill the form'); }else{ $('.msg').html("<img src='loading.gif' border='0' />"); //jQuery ajax post method with $.post('checklogin.php', {email:email, password:password}, function(resp){ if(resp == "cool"){ location.href = 'hiddenpage.php'; }else{ $('.msg').html('Invalid Email or Password'); } }); } });
The above code is already commented, so you can easily understand if you already know a little bit of jQuery. But, anyhow I will explain what is this doing!!
So, there is a button with “id=login” in the “login_form” div. On click of this button $(‘#login’).click() all the other function written inside will work,
1. First it will get the value of email and password.
2. Then it will check if both the values are not empty, if then it will show an error message $(‘.msg’).text()!
3. Thirdly it will call a PHP file via $.post() function.
4. And if the PHP file return a success message “cool“, then it will redirect to the ‘hiddenpage.php‘ otherwise it will show error.
Now the next file is checklogin.php
<?php session_start(); require('db_con.php'); $email = mysql_real_escape_string($_POST['email']); $password = mysql_real_escape_string($_POST['password']); //convert string to md5 $password = md5($password); $sql = "select email, password from user_table where email = '$email' and password = '$password'"; $qry = mysql_query($sql); $numrows = mysql_num_rows($qry); if($numrows > 0){ //set seesion $_SESSION['email'] = $email; //print message for jquery echo "cool"; } ?>
This file is a pure PHP file, which has a normal database operations. First it connects to the database and query the table using SELECT then returns the number of rows. If the number of rows is greater than ZERO it will print “cool“.
Now the Login Operations are over, the second form is Signup, you know it is again same like the above functions.
This jQuery function again comes in index.php
//check if the email is already registered!! $('#email-new').blur(function(){ var email = $('#email-new').val(); if(!validateEmail(email)){ $('.msg').text('Invalid email'); return; } $('.msg').html(''); //checking email $.post('check-email-registered.php', {email:email}, function(resp){ if(resp == 'bad'){ $('.email_err').text('Email not available'); if_record_exist = true; }else{ $('.email_err').text(''); if_record_exist = false; } }); });
The above function will be triggered when the text box loses focus, basically when the cursor comes out of the text box. This script will check if the email enter in the text box is already present in the database or not by calling a PHP file ‘check-email-registered.php‘ and here it the code for that:
<?php require('db_con.php'); $email = mysql_real_escape_string($_POST['email']); $sql = "select email from user_table where email = '$email'"; $qry = mysql_query($sql); $numrows = mysql_num_rows($qry); if($numrows > 0){ echo "bad"; } ?>
I think I don’t have to explain the above script it is same as the ‘checklogin.php‘.
And the final part is after clicking the Signup button, here is the jQuery function:
//when click Signup button $('#signup').click(function(){ //get the values var email = $('#email-new').val(); var password = $('#password-new').val(); //validate the form if(email == '' || password == ''){ $('.msg').text('Please fill the form'); }else{ if(if_record_exist == false){ $('.msg').html("<img src='loading.gif' border='0' />"); //jQuery ajax post method with $.post('adduser.php', {email:email, password:password}, function(resp){ if(resp == "done"){ $('#login_form').show(); $('#signup_form').hide(); $('#options').hide(); $('.msg').html('Signed up successfully, Now use the above form to login!!'); }else{ $('.msg').html('Something is wrong!'); } }); }else{ $('.msg').html('Please fix the above error!'); } } });
This script is again doing the same, get the values from the text boxes and passing it to the PHP file called ‘adduser.php‘ by jQuery $.post() function.
Here is the source code for the ‘adduser.php‘
<?php require('db_con.php'); $email = mysql_real_escape_string($_POST['email']); $password = mysql_real_escape_string($_POST['password']); //convert password to md5 for security $password = md5($password); $sql = "insert into user_table (email, password) values ('$email', '$password')"; $qry = mysql_query($sql); if($qry){ echo "done"; } ?>
The above PHP script will insert a record in the ‘user_table‘.
Other script are like Email validating JavaScript is used:
function validateEmail(email) { var re = /^(([^<>()[].,;:s@"]+(.[^<>()[].,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/; return re.test(email); }
This script validates the email and returns true or false.
Check the demo and download the script here:
Great & Helpful Tutorial. So easy to understand and use, Thanks for sharing with us.
I have also created an Ajax Login Form Using jQuery and PHP.
This is great tutorial for us sir……Thanks