Reading Files With JavaScript Part 2
"That which we persist in doing becomes easier, not that the task itself has become easier, but that our ability to perform it has improved."
Ralph Waldo Emerson
One of the wonderful things about the web is that it makes it so easy to look up information. This is especially true when it comes to finding an answer to a web design problem. For every problem, it seems, there are hundreds code examples on dozens of sites showing how other developers have solved the problem. If you look closely you may find there are really only a few ways to solve a certain problems and most of the code snippets rehash the same old solutions. When looking for code samples on how to read files with JavaScript you will find the same few methods used over and over. Some of those examples are outdated, contain hacks which are no longer needed or are just plain wrong. There is a modern, cross browser and elegant solution available in the remote scripting object, yet you may find few if any examples on the web.
This is Part 2 of our examination on how best to use the remote scripting object to perform this task. [Part 1]
Since the first part of this article was written, nearly all browsers now support remote scripting. The remote scripting object is also slated for inclusion in the W3C's DOM 3 specification for the next generation of web browsers. Thus is a firmly established technology. As of IE 7, you can use the same syntax to create a remote scripting object as is used by Mozilla, Safari, Opera, et. al. and which is also used in the DOM 3 specification.
This version of the code improves error handling, removes some redundant code and adds a couple of options for the developer. Also, the example pages show how to implement this so it degrades nicely in older browsers which do not support the remote scripting object, and for browsers which have disabled JavaScript. A limitation of the previous example was a limitation on the number of includes which could be performed at once. That was changed in subsequent versions of the code, but not mentioned in the article.
To see a live example of using remote scripting to read files into a web page please visit the page at the following link. Read File [Live Example]. The source code for the example is shown on that page. We will look a little closer at that code here.
Our JavaScript calls a function which uses the remote scripting object to get the file at the URL given. The file is simply returned to us as a string of characters, which are loaded into an HTML division. The string returned could be placed in nearly any HTML container or simply written to the browser window using a document.write command. To call the function is simple;
In the example in part 1 we used the body onload event to execute the include(URL) command. The include function can be called in many different ways, including from another function, any page event, a link or a button. As written in the example, the content of the remote page is not returned by the "include" function, but are received by a results handling function.
In this version, we will add additional flexibility by allowing you to specify the results handling function, and optionally a image to indicate contents are loading. So in the improved code, we would use include(URL[, optionalTargetElementId][, optionalLoadingImageSourcePath]);.
//<![CDATA[
// Does this browser support try-catch?
var tc = false;
try {
tc = true;
} catch(f) { }
var xmlHttpError = 'XML HTTP Request: OK'; // for trouble shooting
function getRequestObject() {
var objRequest;
if (window.ActiveXObject) {
if (tc) {
try {
objRequest = new ActiveXObject('Msxml2.XMLHTTP'); // IE 6+
}
catch(e) {
try {
objRequest = new ActiveXObject('Microsoft.XMLHTTP'); // IE 5.5
}
catch(f) { }
}
} else {
objRequest = new ActiveXObject('Microsoft.XMLHTTP'); // ? IE 5.0 ?
}
} else if (window.XMLHttpRequest) {
objRequest = new XMLHttpRequest(); // All other browsers, inc. IE 7 and DOM 3
}
return objRequest;
}
function include(pUrl,pElementId,pImageSrc) {
if (arguments.length==3) { // if an image source is sent
if (pImageSrc) {
document.getElementById(pElementId).innerHTML='<img src="'+pImageSrc+'">'; // load the image while waiting
}
}
if (arguments.length>=3) { // if a targetElement ID is sent
if (pImageSrc) {
document.getElementById(pElementId).innerHTML='<img src="'+pImageSrc+'">'; // load the image while waiting
}
}
var objRequest = getRequestObject(); // create a new request object
if (typeof(objRequest)=='object') { // if we have an object, and
if (objRequest.readyState>=0) { // if the object supports the correct properties...proceed
objRequest.onreadystatechange = function() { handleHttpResponse(objRequest, pElementId); }; // specifiy the function to handle the results
// the correct request object is passed for us.
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; // load the results into the element
pObjRequest=null; // dispose of the now un-needed object.
}
}
}
//-->
//]]>
</script>
You could cut and paste the code into your page's JavaScript block, however it would be better to save that as include.js then add that file to your page with a script tag.
Remote scripting is not available in every browser and will not work if the browser does not have JavaScript enabled. For that reason, the target HTML element can be written to contain an Iframe which loads the page to be included, and we can have a <NOSCRIPT> line in the body to notify the person browsing our page that they need JavaScript enabled to achieve full functionality or to show similar content for browsers which do not support JavaScript, such ass some search engine spiders.
A live example of the client side include function with fallback for non-compliant browsers is available at the following link. [Live Example].
JavaScript Source for the Client Side Include function.
Comment on (or read comments about) this article.
Other Remote Scripting Articles By This Author
AJAHT (AJAX isn't just for XML)
Remote Scripting Images !AJAX
Geo-Coding IP Addresses Using AJAX
Please Wait! (Letting the user know an AJAX call is pending)
HTTP communications with a Server
Reading A Web Server's Response Headers


