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)

Fetch/Extract Data From Database Without Refreshing Webpage: jQuery

Video tutorial illustrating, Fetching / Extraction of Data From Database Without Refreshing Webpage: jQuery + PHP + JSON + MySQL

You need not worry, even if you don’t know any one of these technology. Follow the tutorial, practice and understand, so that you could implement it for your applications.

Also read: Insert Data Into Database Without Refreshing Webpage.

In this tutorial we’ll be showing you, how to extract the data present in our MySQL database table without refreshing the webpage.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
<html>
<head>
<title>Fetch/Extract Data From Database: jQuery + JSON + PHP+ AJAX</title>
</head>
<body>
<ul></ul>
<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 unordered list. We’ll fill it’s list items by extracting the data from the database, using jQuery and PHP.

PHP File: Database Connection Code
db.php

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

Here we’re connecting to the database called company.

Also Read: Connecting To MySQL server From PHP

PHP File: Extracting / Fetching Data From Database table and JSON Encoding
fetch.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< ?php
        include_once('db.php');
 
$sql = "SELECT * FROM people";
$res = mysql_query($sql);
$result = array();
 
while( $row = mysql_fetch_array($res) )
    array_push($result, array('name' => $row[0],
                          'age'  => $row[1],
  'company' => $row[2]));
 
echo json_encode(array("result" => $result));
?>

Here we connect to the database by including db.php file.
Next, select all the fields from the people table.
Extract data one-by-one and store it inside the array variable $result, with key => value pair (associative array).
Finally, using PHP standard function json_encode(), we encode the fetched data.

jQuery File: Accessing The Data And Displaying
my_script.js

1
2
3
4
5
6
7
8
9
10
11
function updates() {
 $.getJSON("fetch.php", function(data) {
       $("ul").empty();
   $.each(data.result, function(){
    $("ul").append("<li>Name: "+this['name']+"</li>
                            <li>Age: "+this['age']+"</li>
                            <li>Company: "+this['company']+"</li>
                            <br />");
   });
 });
}

Using the jQuery AJAX method’s shortcut, $.getJSON() method, we parse fetch.php and process the data passed to the callback function.

We empty the unordered list to avoid duplicate entries later on.

Now loop through all the objects present in the jSON output of fetch.php
Using it’s key, retrieve it’s respective values and append it to the unordered list, as it’s list items.

jQuery File: AJAXing
my_script.js

1
2
3
4
5
6
function done() {
  setTimeout( function() { 
  updates(); 
  done();
  }, 200);
}

Call updates() function and itself[ done() ] inside setTimeout() function with a time gap of 200 milliseconds.

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
$(document).ready( function() {
 done();
});
 
function done() {
  setTimeout( function() { 
  updates(); 
  done();
  }, 200);
}
 
function updates() {
 $.getJSON("fetch.php", function(data) {
       $("ul").empty();
   $.each(data.result, function(){
    $("ul").append("<li>Name: "+this['name']+"</li>
                            <li>Age: "+this['age']+"</li>
                            <li>Company: "+this['company']+"</li>
                            <br />");
   });
 });
}

Call done() once the document is loaded.
You could also call done() function once the window is focused or once some button is clicked or any other user events. This would reduce the database calls considerably.

Fetching / Extraction of Data From Database Without Refreshing Webpage: jQuery


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

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



This would highly enhance the user experience and would help in building rich web applications which look more like desktop / standalone applications.

Please share this video with your friends and also LIKE it on social network sites and on YouTube. Thanks you <3

Related Read:
Insert Data Into Database Without Refreshing Webpage

Fetch JSON Array Elements Using jQuery AJAX Method: getJSON

Video tutorial illustrates the extraction of JSON Array elements using jQuery AJAX method: getJSON

Here we extract data(JSON ARRAY) from an external JSON file, which has a file extension .json

HTML code
index.html

1
2
3
4
5
6
7
8
<html>
<head><title>Fetch JSON array Data</title></head>
<body>
<ul></ul>
<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 unordered list. We’ll be filling it’s list items from the JSON file using jQuery.

JSON File
json_data.json

1
2
3
4
5
6
{
 "person": [  
     { "name": "Satish", "age": 25 },
     { "name": "Shwetha", "age": 24 }
 ]
}

Here we have a key called “person”, which is a JSON array.
“person” has two elements in it, which are objects.
Each object has two key => value pairs.
The key being, name and age.

jQuery Code
my_script.js

1
2
3
4
5
6
7
8
$(document).ready( function() {
 $.getJSON("json_data.json", function(data){
       $.each(data.person, function(){
         $("ul").append("<li>Name: "+this['name']+"</li>
                                <li>Age: "+this['age']+"</li>
                                <br />");
   });
 });

Once the document loads, we call an anonymous function. Inside that, we call the shortcut function of jQuery AJAX method i.e., $.getJSON method.
The first parameter is the file to be parsed, second parameter is the callback function.

Inside the callback function, we loop through the array elements and fetch the values using its key names, and finally append it to the unordered list of index.html

Fetch JSON Array Elements Using jQuery AJAX Method: getJSON


[youtube https://www.youtube.com/watch?v=VAMz-fcDNhs]

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



To make the AJAX effect, you could write the jQuery coding inside a custom function and then call it for setTimeout() function etc:
setTimeout(customFunction, 4000);
setInterval(repeatFunctionCall, 4000);
slideDown().delay(4000).slideUp(); ( Chain method )