Developing the Client-Side Code for Server-Side Data Validation with AJAX - Integrating the client-side application layer: listing all of the JavaScript functions
(Page 5 of 5 )
As I mentioned in the previous section, below I listed all the JavaScript functions that comprise the client-side application layer. Please take a look:
var errors=new Array();
// send http requests
function sendHttpRequest(url,callbackFunc,respXml){
var xmlobj=null;
try{
xmlobj=new XMLHttpRequest();
}
catch(e){
try{
xmlobj=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
alert('AJAX is not supported by your browser!');
return false;
}
}
xmlobj.onreadystatechange=function(){
if(xmlobj.readyState==4){
if(xmlobj.status==200){
respXml?eval
(callbackFunc+'(xmlobj.responseXML)'):eval
(callbackFunc+'(xmlobj.responseText)');
}
}
}
// open socket connection
xmlobj.open('GET',url,true);
// send http header
xmlobj.setRequestHeader('Content-Type','text/html;
charset=UTF-8');
// send http request
xmlobj.send(null);
}
// initialize form and assign events
function initializeForm(){
document.getElementsByTagName('form')[0].elements
[3].disabled=true;
var elems=document.getElementsByTagName('form')[0].elements;
if(!elems){return};
for(var i=0;i<elems.length;i++){
// check for 'required' attribute
if(elems[i].getAttribute('required')){
elems[i].onblur=function(){
// validate current field
sendHttpRequest('validator1.php?
field='+this.getAttribute('name')
+'&value='+this.value+'&method='+this.getAttribute('required')
+'&message='+this.getAttribute
('title'),'displayErrorMessage',false);
}
}
}
}
// display error messages
function displayErrorMessage(serverResponse){
var elemkey=serverResponse.split('|')[0];
var errormsg=serverResponse.split('|')[1];
var counter=0;
var msgcont=document.getElementById('msgcontainer');
if(msgcont){msgcont.parentNode.removeChild(msgcont)};
var msgcont=document.createElement('div');
msgcont.setAttribute('id','msgcontainer');
// assign error values to error counters
errors[elemkey]=(errormsg==' ')?0:1;
// count total errors
for(var i in errors){if(errors[i]){counter++}};
var btn=document.getElementsByTagName('form')[0].elements[3];
if(!counter){
// if no errors were found enable submit button
btn.disabled=false;
var errormsg='Data is Ok. Now submit the form, please.';
}
else{
// if errors were found enable submit button & display
error message
btn.disabled=true;
}
msgcont.appendChild(document.createTextNode(errormsg));
document.getElementById('formcontainer').appendChild
(msgcont);
}
// run 'initializeForm()' function when page is loaded
window.onload=function(){
// check if browser is DOM compatible
if(document.createElement&&document.getElementById
&&document.getElementsByTagName){
initializeForm();
}
}
As you can see, that’s all the JavaScript functions that compose this AJAX-drive program. However, the prior code listing would be rather incomplete if I didn't show you the corresponding (X)HTML markup and the CSS declarations that also play a relevant role, in order to get the application working. Therefore, here they are:
<style type="text/css">
body {
margin: 0;
padding: 0;
}
p{
text-align: center;
font: bold 24px Arial, Tahoma;
color: #000;
}
p{
font: bold 12px Arial, Tahoma;
color: #000;
text-align: right;
margin-right: 50px;
}
#formcontainer{
width: 350px;
height: 300px;
padding: 5px;
background: #efdfff;
border: 1px solid #ccc;
margin-left: auto;
margin-right: auto;
}
#msgcontainer{
width: 300px;
height: 30px;
padding: 10px;
font: bold 12px Arial;
color: #f00;
text-align: center;
}
.inputbox{
width: 200px;
font: normal 12px Arial;
color: #000;
}
.formbutton{
width: 100px;
font: normal 12px Arial, Tahoma;
color: #000;
}
</style>
</head>
<body>
<div><p>AJAX-BASED FORM VALIDATOR</p></div>
<div id="formcontainer">
<form method="post" action="nextpage.php">
<p>First Name <input name="fname" type="text"
required="Empty" class="inputbox" title="Enter your First Name
(at least 8 characters)" /></p>
<p>Last Name <input name="lname" type="text"
required="Empty" class="inputbox" title="Enter your Last Name (at
least 8 characters)" /></p>
<p>Email <input name="email" type="text"
required="EmailWin" class="inputbox" title="Enter a valid email
address" /></p>
<p><input type="submit" value="Send Data"
class="formbutton" /></p>
</form>
<div>
</body>
</html>
To wrap up
In this second article of the series, I provided you with the complete set of JavaScript functions, aimed at sending HTTP requests in the background, as well as displaying error messages and controlling the flow of data validation. If you’re used to working with requester objects, then all these concepts should be easy for you to grasp.
Over the last tutorial, I’ll develop the PHP routines, tasked with validating several types of user-supplied input, in order to get the AJAX-driven form validation program completed. If you wish to know how this story ends, don’t miss the last chapter!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |