Developing the Client-Side Code for Server-Side Data Validation with AJAX - Controlling the flow of data validation: defining the “initializeForm()” function
(Page 4 of 5 )
It's quite possible that now you’re wondering how the flow of data validation is controlled inside the application. Well, in this case, I decided to trigger an HTTP request to the server each time the user moves the focus out of a particular form field by using the “onblur” event handler, but this behavior can be improved or even entirely changed to provide the application with better usability and accessibility.
Having said that, below I listed the source code of the “inititializeForm()” function, which looks like this:
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);
}
}
}
}
As you can see, the above function doesn’t bear much discussion, so I'll explain quickly what it does. First, it disables the submitting button of the online form, and next attaches the “sendHttpRequest()” function to all the input boxes that have a “required” attribute. Undoubtedly, this part of the function is the most important one, and should be appropriately evaluated, in case that you may want to use another event handler.
Okay, at this stage you hopefully learned how the flow of input validation is entirely controlled by the function that you saw before. But I’m pretty sure that you want to see the complete list of JavaScript functions that I defined earlier. To examine the full source code that corresponds to the client-side layer of this AJAX application, all you have to do is jump into the next section and keep reading.
Next: Integrating the client-side application layer: listing all of the JavaScript functions >>
More JavaScript Articles
More By Alejandro Gervasio