Form Validation Using AJAX

Thursday 28 April 2011 Posted by Sridharan Natarajan 4 comments
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:

Introduction to AJAX

Saturday 23 April 2011 Posted by Sridharan Natarajan 1 comments
AJAX is an acronym for Asynchronous JavaScript and XML and it is a technique that allows the web pages to be updated asynchronously without refreshing the entire page. It gives better user experience, interactive web pages and seamless server communication.

You can implement AJAX in the following way:

1. Create XMLHttpRequest object
    AJAX uses the XMLHttpRequest object to exchange data asynchronously with  the web server. This XMLHttpRequest object is having the following states:
readyState Status Codes:
0 = uninitialized (Request to the server is not initialized)
1 = loading (Connection to the server is established)
2 = loaded (Request to the server has been loaded)
3 = interactive (Request is in process)
4 = complete (Response is processes and the response is sent)
This state is called readyState.This is the important property of the XMLHttpRequest object.

The readyState 4 means, the request has been processed and the response is received.

2. Define a call back function that will be called whenever the state of the XMLHttpRequest object is changed. The event is called onreadyStateChanged.
Status is an another important property that holds the status of the response returned from the server.
Ex.
200: "OK"
404: Page not found

3. Send the request.

4. Most importantly the responseText/responseHTML holds the actual body of the response.  This can be displayed in any part of the web page.

Now we will see how to implement the above steps.
<html>
<head>
<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 getEmpName(){
  var empId = document.getElementById("getEmpName").value;
  var xmlhttp = getXMLHttpReqObject();

  if(xmlhttp != null){
     xmlhttp.onreadystatechange = displayName;
     xmlhttp.open("GET","getEmpName.php?empId=" + empId,true);
     xmlhttp.send();

  }

}

//this is the callback function that will be called whenever the readystate is changed.
function displayName(xmlhttp){
  
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
  {
    document.getElementById("empName").innerHTML = xmlhttp.responseText;
  }
  
} 

</script>

</head>

<body>
   <form>
     Enter Emp Id <input type="text" name="empId" value="" /> &nbsp;
<input type="button" name="getEmpName" id="getEmpName" value="Get Emp. Name" onClick="getEmpName();"/> </br>
Employee Name: <span id="empName"></span>
   </form>
</body>

</html>

Labels: