* Updated 7-02-2007. Refined code.
* Updated 4-03-2007. Added Try-Catch blocks for a few bad browsers which were slipping through.
* Updated 3-27-2006. Added error message for browsers which do not support the XMLHTTP object.
The division below, with the ID of "theExample" was loaded as follows <script>include('latin.htm','theExample');</script>. Since JavaScript does not have a native include function, you will need to include a short JavaScript file in the head section of your page. <script type="text/javascript" src="include.js"></script>. The code for include.js is listed below and can be downloaded as a zip archive [here].
Note: [Full Article] You are also not
restricted to using this function on page load. It may be called anytime from any event. For example;
<a href="#" onclick="include('latin.htm','theExample');">Click Me to Load</a>.
// Does this browser support try-catch?
var tc = false;
try {
tc = true;
} catch(f) { }
var xmlHttpError = 'XML HTTP Request: OK';
function getRequestObject() {
var objRequest;
if (window.ActiveXObject) {
if (tc) {
try {
objRequest = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e) {
try {
objRequest = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(f) { }
}
} else {
objRequest = new ActiveXObject('Microsoft.XMLHTTP');
}
} else if (window.XMLHttpRequest) {
objRequest = new XMLHttpRequest();
}
return objRequest;
}
function include(pUrl,pElementId,pImageSrc) {
if (arguments.length==3) {
if (pImageSrc) {
document.getElementById(pElementId).innerHTML='<img src="'+pImageSrc+'" width="16" height="16">';
}
}
var objRequest = getRequestObject();
if (typeof(objRequest)=='object') {
if (objRequest.readyState>=0) {
objRequest.onreadystatechange = function() { handleHttpResponse(objRequest, pElementId); };
objRequest.open('GET', pUrl, true);
objRequest.send(null);
}else{
xmlHttpError = 'XML HTTP Request Object Unavailable';
return false;
}
}else{
xmlHttpError = 'XML HTTP Request Object Not Supported';
return false;
}
}
function handleHttpResponse(pObjRequest, pElementId) {
if (pObjRequest.readyState==4) {
if (pObjRequest.status==200) {
document.getElementById(pElementId).innerHTML=pObjRequest.responseText;
pObjRequest=null;
}
}
}
Date Validation Using JavaScript .
Cross-Browser Clipboard Copy .
Loading Images With Remote Scripting .
Why JavaScript In Hyperlinks Is Bad .
Change The Submit Button To Show Waiting For AJAX Response .
European Date Validation Using JavaScript .
Database Results To Client Side Array .
Reading Files With JavaScript .
AJAX For Plain Text And HTML .