Registration Form Validation: PHP + jQuery + AJAX (PART 2)

In this video tutorial we illustrate both client side as well as server side validation.

Client side validation using jQuery.
Server side validation using PHP.

To Solve:
Empty values shouldn’t be registered.
Duplicate usernames must not be allowed.
Display appropriate message, in case of duplicate username.

Explanation about HTML file (index.html), Database connection file(db.php):
Registration Form Using jQuery + PHP + AJAX (PART 1)

jQuery File: Client Side Validation
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$("#submit").click( function() {
 
if( $("#username").val() == "" || $("#pass").val() == "" )
  $("#ack").html("Username/Password are mandatory fields -- Please Enter.");
else
  $.post( $("#myForm").attr("action"),
         $("#myForm :input").serializeArray(),
 function(info) {
 
   $("#ack").empty();
   $("#ack").html(info);
clear();
 });
 
$("#myForm").submit( function() {
   return false;
});
});
 
function clear() {
 
$("#myForm :input").each( function() {
      $(this).val("");
});
 
}

If the username and the password fields are empty, we display appropriate message and skip the execution of $.post() method.
This ensures that, we do not request data from the server when there is no need for it.

If the user has entered both username and password, then we execute $.post() method and pass the user entered data to process.php file.

PHP File: Server Side Validation
process.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
< ?php
      include_once('db.php');
 
  $username = mysql_real_escape_string( $_POST["username"] );
  $password = mysql_real_escape_string( md5($_POST["pass"]) );
  $fname = mysql_real_escape_string( $_POST["fname"] );
  $lname = mysql_real_escape_string( $_POST["lname"] );
 
 
  if( empty($username) || empty($password) )
  {
  echo "Username and Password are mandatory - from PHP!";
exit();
  }
 
 
 $res = mysql_query("SELECT username FROM users WHERE username='$username'");
  $row = mysql_fetch_row($res);
 
  if( $row > 0 )
    echo "Username $username has already been taken";
  else
  {
     $sql = "INSERT INTO users VALUES('',
                                           '$username', 
                                           '$password', 
                                           '$fname', 
                                           '$lname')";
    if( mysql_query($sql) )
     echo "Inserted Successfully";
   else
     echo "Insertion Failed";
}
?>

At the beginning we check if the username or the password is empty. If they are empty, we echo Username and Password are madatory – from PHP and then stop further execution of the script.

If the username and password are not empty, then we check the user entered username against the usernames present inside the database. If the username is already present inside the database, then we intimate it to the user with a customized message.

Registration Form Validation: PHP + jQuery + AJAX (PART 2)


[youtube https://www.youtube.com/watch?v=dRk1r4SfSyA]

YouTube Link: https://www.youtube.com/watch?v=dRk1r4SfSyA [Watch the Video In Full Screen.]



Why Validate both client side as well as server side ?
What if javascript has been disabled on client machine i.e., the browser ?
In this situation, our client side validation completely fails. So, server side validation is also important.

Then Why client side validation when server side validation could serve our purpose ?
This is because, client side validation is faster. i.e., if user tries to register empty data, it needs to travel across, reach the server, execute the validation rules script and then travel back to report that the user had submitted empty data and is not acceptable!
Instead of this lengthy, time consuming and costly process, we could simply write a client side validation and it responds back instantly, saving time, bandwidth and hence the cost of processing the data.

Registration Form Using jQuery + PHP + AJAX (PART 1)

Video tutorial illustrates development of user registration form using jQuery AJAX method.
In this tutorial we shall build a registration form using which users can register without leaving the webpage. i.e., without being redirected to any other pages once he / she hits the submit/register button.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html>
<head><title>Registration Form: jQuery</title></head>
<body>
 
<form id="myForm" action="process.php" method="POST">
Username: <input type="text" name="username"/><br />
Password: <input type="password" name="pass"/><br />
First Name: <input type="text" name="fname"/><br />
Last Name: <input type="text" name="lname"/><br />
<button id="submit">register</button>
</form>
 
<div id="ack"></div>
 
<script type="text/javascript" src="script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="script/my_script.js"></script>
</body>
</html>

Here we have a simple form with username, password, first name, last name fields and a button. Also a div with an id of ack where appropriate messages are displayed to the users.

Form has an id of myForm.
process.php file in the action field.
POST method.

PHP File: Database Connection Code
db.php

1
2
3
4
< ?php
      $conn = mysql_connect('localhost', 'root', '');
  $db   = mysql_select_db('people');
?>

Here we’re connecting to the database called people.

Also Read: Connecting To MySQL server From PHP

Database Details:
Database Name: people
Table Name : users
Fields : slno, username, password, fname, lname.

PHP File: Inserting user entered data to database table
process.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
< ?php
      include_once('db.php');
 
  $username = mysql_real_escape_string( $_POST["username"] );
  $password = mysql_real_escape_string( md5($_POST["pass"]) );
  $fname = mysql_real_escape_string( $_POST["fname"] );
  $lname = mysql_real_escape_string( $_POST["lname"] );
 
  $sql = "INSERT INTO users VALUES('',
                                           '$username', 
                                           '$password', 
                                           '$fname', 
                                           '$lname')";
  if( mysql_query($sql) )
   echo "Inserted Successfully";
  else
   echo "Insertion Failed";
?>

Here we use mysql_real_escape_string() method to avoid sql injection by the user.
We accept all the values entered by the user and store them in php variables.

Later we formulate MySQL query and pass these user entered values to it and execute it using mysql_query() PHP method.

Using the conditional logic statement we check if the query got executed or not. Then output appropriate message using echo.

This message will be retrieved by the call back function in jQuery and is being further processed as required.

jQuery File: Accessing The Data And Displaying
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
$("#submit").click( function() {
 $.post( $("#myForm").attr("action"),
         $("#myForm :input").serializeArray(),
 function(info) {
 
   $("#ack").empty();
   $("#ack").html(info);
 });
 
$("#myForm").submit( function() {
   return false;
});
});

Once the user clicks on the button with an id submit, we call $.post() method.
First parameter being the URL to which the data is being sent.
Second parameter is the actual data, which is being serialized using serializeArray() method of jQuery. It formats the user entered data into key => value pairs.
Third parameter, is the call back function.

Using the data returned by process.php we display the data in div tag with an id of ack.

We also disable the redirection of the webpage by returning false once the user clicks on the button.

jQuery File: Clearing the input fields
my_script.js

1
2
3
4
5
6
7
function clear() {
 
$("#myForm :input").each( function() {
      $(this).val("");
});
 
}

It’s a custom function which selects all the input fields, loops through them and assigns an empty value.

jQuery File: Full / Final Code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$("#submit").click( function() {
 
 $.post( $("#myForm").attr("action"),
         $("#myForm :input").serializeArray(),
 function(info) {
 
   $("#ack").empty();
   $("#ack").html(info);
clear();
 });
 
$("#myForm").submit( function() {
   return false;
});
});
 
function clear() {
 
$("#myForm :input").each( function() {
      $(this).val("");
});
 
}

Call clear() method after the user entered data is processed.

Registration Form Using jQuery + AJAX: PART 1


[youtube https://www.youtube.com/watch?v=55FwdtnvQAM]

YouTube Link: https://www.youtube.com/watch?v=55FwdtnvQAM [Watch the Video In Full Screen.]



This way we turned our traditional registration form to a standard AJAX application form.

In tomorrows video tutorial lets see client side validation using jQuery and server side validation using PHP.

Registration Form Validation: PHP + jQuery + AJAX (PART 2)