This is a simple usage example of Ajax that shows how to update a part of the HTML page without refreshing the page. This is a great GUI advantage which makes the application look more like a windows application rather then a web based client side application.
The SELECT field triggers a call to UpdateDiv which does all of the work. UpdateDiv gets the parameter from the SELECT and passes it on so we can act upon it.
UpdateDiv Gets two parameters :
1. A URL for a Web Service that returns any kind of output based on the parameter we passed.
2. A name of a function that will be triggered when the data comes back. This function usually takes HTML output from the remote URL and populates the DIV we prepared with the HTML using innerHTML.
The data will be put in <DIV NAME="MyDiv" ID="MyDiv"> that we can locate wherever we like.
// Initialize XMLHttpObject
function CreateXmlHttpObject(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
var objXMLHttp = new XmlHttp();
function GetReadyState( ){
return this.objXmlHttp.readyState;
}
function GetResponseText( ){
return this.objXmlHttp.responseText;
}
// Function performs Get request to absolute url(strUrl)
// using XmlHttp object (asynchroni)
// Response returned into objResult element using innerHTML.
// When state of XmlHttp object is changed - objOnReadyStateChangeFunction called
function GetUrlContent( strUrl, objOnReadyStateChangeFunction ){
this.objXmlHttp.open(this.HttpMethod, strUrl, true);
this.objXmlHttp.setRequestHeader('Content-Type', 'text/xml; charset=UTF-8');
if(objOnReadyStateChangeFunction){
this.objXmlHttp.onreadystatechange=function(){
objOnReadyStateChangeFunction();
}
}
this.objXmlHttp.send(null)
}
//This function is called when we get the data back from the server.
function GetResponse( ){
if (objXMLHttp.GetReadyState()==4) {
// save response in inner html of result object
var objMyDiv = document.getElementById( 'MyDiv' );
objMyDiv.innerHTML = objXMLHttp.GetResponseText( );
}
}