Form Validation Using AJAX

Thursday, 28 April 2011 Posted by Sridharan Natarajan
Form Validation is the most important feature in any web site that accepts inputs from the world wide users.
In older days, if anything needs to be validated against the existing data in DB, we have to submit the form, validate it in the server and then reloads the page to display the error message. So, the call to the server is explicitly visible to the user.
Now, lets look at how AJAX deals this and bring it to the implicit server call, validates and displays the message in the browser without reloading the page.

Most of the web-sites are having sign-up/register forms to allow users signed-up to their site. There should be a unique username to each users to identify them. So, the usernames entered in the Register form should validated against the existing usernames, so that someone should not avail the username that was already chosan by another user. This validation can be done only in server side.

We will see the step by step implementation for checking the availability of the username chosan.

1. Create a Sign-up form. I have only username text box and Check Availability Button. But, in real-time, there can be lot of fields like, First Name, Last Name, username, password, email and etc. For the explanation of AJAX validation, I considered only username field.


<html>
 <head><title>Form Validations Using AJAX</title></head>
<body>
<form name="register" action="register.php">
<div id="res_msg"></div> 
<label>Enter User Name : </label><input type="text" name="username" value="" /> <br/>
<input type="button" name="check_username" value="Check Availability" onClick="checkAvailability();" />
</form>
</body>
</html> 

The div,<div class="res_msg"></div>, in the above code is just a place holder to display the response message received from the AJAX call.
The button calls the javascript function checkAvailability(). Once the button is clicked, this function will be invoked. We will create the function in the next step.

2. Now, create a XMLHTTPRequest and send a request to the server.

Add the below code inside the <head> tags in the above HTML code.

<script type="text/javascript">

//This creates XMLHttpRequest for various browsers
function getXMLHttpReqObject(){
  var xmlhttp = null; 
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 
  return xmlhttp;

}

function checkAvailability(){
  var username = document.register.username.value;
  var xmlhttp = getXMLHttpReqObject();

  if(xmlhttp != null){
     xmlhttp.onreadystatechange = processCheckAvailability;
     xmlhttp.open("GET","register.php?username=" + username,true);
     xmlhttp.send();

  }

}
</script>



The checkAvailability() functions, creates a XMLHTTPRequest for register.php and sends the request.

3. The next step is to write a callback function processCheckAvailability(). This callback function will be called whenever the readyState value is changed. As you know, the response will be available only when the readyState is 4.

Add the below code inside the <script> tags.
function processCheckAvailability(xmlhttp){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
  {
    document.getElementById("res_msg").innerHTML = xmlhttp.responseText;
  }
}

4. Now this is the time to write the server side script that actually validates the input.
Add the following code to register.php
//add code to create a DB connection and selectDB
if(!empty($_POST) and !empty($_POST[´check_username´])){
$sql = "SELECT COUNT(*) AS cnt FROM tbl_users WHERE username=´".$_POST[´username´]."´";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if($row[´cnt´] == 0){
echo "Username is available.";
}else{
echo "Username is not available.";
}
}

Now, the AJAX way of doing a form validation is ready.
Labels:
  1. Nice Post...Good insight about ajax.

  2. Good one buddy. I like the blog layout. It is pretty neat and professional.

  3. Good points to help us

  4. Nice Post Sridhar. Keep this coming.

Post a Comment