PHP Form Validation With AJAX

In the previous article, we went through the process of server side validation of form data on submitting the form. It is a pretty good way of validating forms but a need may still arise for validating a form's data without submitting it. I prefer doing it using AJAX.

How does AJAX work?

Simple XMLHttpRequest in AJAX must go through the four phases:

  • XMLHttpRequest Object
  • XMLHttpRequest Request
  • XMLHttpRequest Response
  • XMLHttpRequest readyState

These several phases can be summarized as follows.

Object

It is responsible for exchanging the data from the server behind the scene, i.e., without reloading the page.

Request

A request through an object is manipulated using the two functions:

open(method, url, async)

method: the type of request – GET or POST
url: server file location
async: true (asynchronous) or false (synchronous)

Response

In order to receive a response from the server, we will use the responseText property of the XHR object.

ReadyState

The readyState property holds the status of the XMLHttpRequest.

The Onreadystatechange event is triggered everytime the readystate changes.

The ReadyState varies from 0 to 4, which represents:

0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready;
the status property of XMLHttpRequest holds the two values:
200: "OK"
404: page not found

Summary

A Form contains multiple textfileds, data under which may be needed to be validated. We do it by calling the AJAX function, everytime the text inside the textfield changes.

The response text is placed under the <div> located right next to the textfield for the ease of displaying validation messages.

index.php

<html>

            <head>

                        <script type='text/javascript'>

                                    function validate(field, query)

                                    {

                                                xmlhttp = new XMLHttpRequest(); // Creating Object

                                                xmlhttp.onreadystatechange = function() // Checking if readyState changes

                                                {

                                                            if (xmlhttp.readyState!=4 && xmlhttp.status==200) // Validation Under Process

                                                            {

                                                                        document.getElementById(field).innerHTML = "Validating..";

                                                            }

                                                            else if (xmlhttp.readyState==4 && xmlhttp.status==200) // Validation Completed

                                                            {

                                                                        document.getElementById(field).innerHTML = xmlhttp.responseText;

                                                            }

                                                            else // If an error is encountered

                                                            {

                                                                        document.getElementById(field).innerHTML = "Unknown Error Occurred. <a href='index.php'>Reload</a> the page.";

                                                            }

                                                }

                                                xmlhttp.open("GET","check.php?field="+field+"&query="+query, false);

                                                xmlhttp.send();

                                    }

                        </script>

            </head>

            <body>

                        <form action='#' method='post'>

                                    <table>

                                                <tr>

                                                            <td>Username</td>

                                                            <td><input type='text' name='user' onchange="validate('user', this.value)"></td>

                                                            <td><div id='user'></div></td> // Div to hold validation message

                                                </tr>

                                                <tr>

                                                            <td>Password</td>

                                                            <td><input type='password' name='pass' onblur="validate('pass', this.value)"></td>

                                                            <td><div id='pass'></div></td>

                                                </tr>

                                    </table>

                                    <input type='submit' value='Submit'>

                                    <input type='hidden' name='form' value='1'>

                        </form>

            </body>

</html>

check.php
 

<?php

$query = $_GET['query']; // holds the input data

$field= $_GET['field']; // holds the name of field

if($field == "user")

{

            $username = array("shashank", "srivastava");

            if(in_array($query, $username)) echo "<font color=red>Username already exists</font>";

            else echo "<font color=green>Username available</font>";

}

else if($field == "pass")

{

            if(strlen($query) < 6) echo "<font color=red>Password too short</font>";

}

?>

PHP-AJAX.jpg

Kindly submit suggestions for improving this process.
 

Up Next
    Ebook Download
    View all
    Learn
    View all