Let’s take a scenario where server side validation is required to check whether employee is already in a project or not.
$(document).ready(function(){
$("#associateID").blur(function(){
var assId = $("#associateID");
//checkAssociateId function returns true if employee is already available in DB
if(checkAssociateId(assId.val())){
// Display message and set focus on Associate ID field
$('#spnassociateID').html('Associate is already On-boarded');
$('#spnassociateID').css('color', 'red');
$('#spnassociateID').css( 'font-size', 'small');
$("#associateID").focus();
return false;
} else{
$('#spnassociateID').html('ID is accepted and not available in project data base');
$('#spnassociateID').css('color', 'green');
$('#spnassociateID').css( 'font-size', 'small');
return true;
}
})
})
function
//checkAssociateAjaxCall returns "not-available" if associate id is not present in employee_details
var
result = checkAssociateAjaxCall(id);
if
(result.indexOf("not-available")>=0){
return
false;
}else
{
return
true;
}
// checkAssociateAjaxCall actually do the Ajax call
function
checkAssociateAjaxCall(id)
{
// Ajax implementation
var
result;
var
xmlhttp;
// random parameter is added to make each request unique other wise cache will automatically take previous result without hitting DB
var
strURL = "validateAssociateId?associateId="+ id + "&random=" + Math.random(); ;
if
(window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=
new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=
new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=
function()
{
{
result = xmlhttp.responseText;
}
}
xmlhttp.open(
"GET",strURL,false);
xmlhttp.send();
}
Step 2: In Above code calling "validateAssociateId" action thus add below piece of code in struts configure xml (struts.xml).
<
action name="validateAssociateId"
Step 3: In OnboardEmployeeAction struts action class define followings
private static String BLANK ="";// declare a inputStream and gette setter for in
}
String result=
BLANK;
// ValidateTask calls validateAssociateId method which returns either "success" or "error"
// PLease implement back end code as per your requirement
ValidateTask validateTask = new ValidateTask();
result = validateTask.validateAssociateId( associateId);
// inputStream = new ByteArrayInputStream("available".getBytes("UTF-8"));
}
else{
// inputStream =new ByteArrayInputStream("not-available".getBytes("UTF-8"));
}
}