Developing the Client-Side Code for Server-Side Data Validation with AJAX - Triggering HTTP requests in the background: meet the world of requester objects
(Page 2 of 5 )
In order to start developing all the JavaScript functions that integrate this particular application, I first must work with requester objects. In this way I will provide the data checking system with the ability to perform HTTP requests without having to reload the web page, and to call the corresponding input validation routines on the server.
To achieve all the tasks that I described above, here is the definition of the “sendHttpRequest()” function. As the name suggests, it is responsible for triggering HTTP requests silently. Please examine the code listed below:
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);
}
This is pretty simple. As you can see, the function listed above takes three parameters to do its business: first, the URL to which the request will be made, then the name of the callback function that will process the response sent back by the server, and finally a Boolean flag indicating whether the corresponding server response will be expected as plain text (that is, using the “responseText” property), or as XML (utilizing the “responseXML” property).
To finish describing the previous function, let me tell you that it will also create an XMLHttpRequest object in a cross-browser fashion, and send out all the requests via the GET method. Short and simple, isn’t it?
Well, now that I have a requester object to work with, the next logical step consists of defining the respective callback function. This function processes all the responses sent by the server, whether a particular value entered in the form field was considered valid or not. Are you starting to see how this AJAX-based data validating application will work? I hope you are!
Over the next few lines, I’ll be defining the brand new “displayErrorMessage()” JavaScript function, which will handle the respective server responses after calling a specific PHP validation routine. Click on the link below and keep reading.
Next: Processing server responses: defining the “displayErrorMessage()” function >>
More JavaScript Articles
More By Alejandro Gervasio