Here is the code I wrote for ajax validation. I haven't yet created the submit button for the form. The problem is, I have to disable the submit button till all the fields are filled with appropriate information and validated in ajax way. This is just a sample with two fields. I've more than 20 fields like this.Please help me to do this. Thank you.
Form:
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="50" minlength="2"onkeyup="checkname()"/>
<span id="target1"></span></p>
<p>
<label for="fat">Father's Name</label>
<em>*</em><input id="cfat" name="father" size="50" onkeyup="checkfather()" />
<span id="target2"></span></p>
Javascript(ajax):
var ajax = create_ajax_object();
function checkname(){
if(ajax){
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
document.getElementById("target1").innerHTML = ajax.responseText;
}
}
ajax.open("POST", "ajval.php", true);
var values = "name=" + encodeURIComponent(document.commentform.name.value);
values = values + "&action=" + encodeURIComponent("check1");
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send(values);
}
else{
alert("Your browser doesnt support AJAX!");
}
}
function checkfather(){
if(ajax){
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
document.getElementById("target2").innerHTML = ajax.responseText;
}
}
ajax.open("POST", "ajval.php", true);
var values = "father=" + encodeURIComponent(document.commentform.father.value);
values = values + "&action=" + encodeURIComponent("check2");
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send(values);
}
else{
alert("Your browser doesnt support AJAX!");
}
}
PHP:
<?php
$action = $_POST["action"];
switch($action)
{
case "check1":
$name=$_POST["name"];
if($name!="")
echo '<img src="green-tick.png" height="20" width="20"/>';
else
echo'<span style="color:red;">Cannot be left blank</span>';
break;
case "check2":
$father=$_POST["father"];
if($father!="")
echo'<img src="green-tick.png" height="20" width="20"/>';
else
echo '<span style="color:red;">Cannot be left blank</span>';
break;
?>