Form validation through Ajax

               Before going through the concepts of Ajax just have some views about why we use Ajax. In the classic web pages, after entering the form completely only it has to be submitted and then verify that data like username and others, or to get a particular username in the server side. If the data loaded is incorrect then again the form should be completed. This becomes irritating to some users to enter data again. When we use Ajax in web pages  user will get rid of these irritations as the form will be validated against the server side as the user enters the values. Here various can be set upon, like when one field looses the focus after entering that field is validated. Here data is sent asynchronously without waiting the user submission. This makes the user feel some ease. Here the asynchronous work is done by "xmlhttp" silently. This will query the database and will return the data to the main page.
           Another drawback of using forms in classic web pages is when the form is submitted, entire page is reloaded and all the elements should be reloaded which will take more time and also data. Here by using ajax forms this can be controlled. Lets see one simple example which will demonstrate this. Here the form will check for the username present or not. 


1) Create table in database
Create table username(name char(20));


insert into username values('vijay');
insert into username values('raam');



2) Form.html
<html>
<head>
<script type="text/javascript" src="checksignupuser.js"></script>
</head>
<body>
 <form >
<input type=text name=name onblur="showUser(this.value)" >
<input type=text name=ss>
<input type=submit value=enter>
</form>
<br/>
<div id="status"><b> status here.</b></div>
 </body>
</html>



3)checksignupuser.js
var xmlhttp;
function showUser(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Browser does not support HTTP Request");
  return;
  }
var url="checksignupuser.php";
url=url+"?name="+str;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("status").innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // checking IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // checking IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}



4)checksignupuser.php
 
$name=$_GET["name"];
$mysql= mysql_connect('localhost', 'apache', 'abc123');

mysql_select_db("temp");
$sql="select * from username where name = '$name'";
$result = mysql_query($sql);
$a=mysql_fetch_array($result);

if($a)
{
print "$a[name] present ";
}
else
print "$a[name] not present ";

 mysql_close($mysql);
?>

This completes the code for the Ajax form. Copy the code and enjoy.