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.


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


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)


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


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


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.




                        <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.";



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






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




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

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




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

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



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

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






$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>";




Kindly submit suggestions for improving this process.

Up Next
    Ebook Download
    View all
    View all