Displaying Dynamic Content with Pop Up DIVs with the DOM and AJAX - Adding the functionality of AJAX to the existing application
(Page 3 of 4 )
As I stated in the section that you just read, the next step involved in making the pop-up DIVs truly dynamic consists of creating two additional JavaScript functions. The first one will be tasked with sending HTTP requests in the background via AJAX, while the second one will be responsible for populating the respective pop-up DIVs with content fetched from the server.
As you’ll see soon, the functionality provided by these two new functions will allow the mentioned DIVs to display data that comes from a text file located on the web server. Do you see how the application now handles a dynamic feature? I bet you do!
All right, having explained the useful tasks performed by these functions, you'll want to look at their respective signatures. Here they are:
// 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);
}
// display fill pop-up DIVS with server contents
function displayResults(content){
var popupdiv=document.getElementById('popup');
if(!popupdiv){return};
popupdiv.innerHTML='';
popupdiv.innerHTML=content;
}
As shown above, the first function uses the functionality provided by cross-browser HTTP requester objects to fetch a specific file in the server, while the second one simply receives the corresponding contents and displays them inside a DIV element, identified as “popup.” Pretty simple, isn’t it?
However, the isolated definitions for these brand new JavaScript functions don’t tell anything about the way they work in the context of the application itself. Therefore it’s necessary to put all the pieces together and demonstrate how any pop-up DIV included in the corresponding web document is now capable of displaying data fetched from the server.
Want to learn how this will be done? Okay, click on the link that appears below and read the following section. We’re almost finished!
Next: Completing the application >>
More JavaScript Articles
More By Alejandro Gervasio