Skip To Main Content | Home | Sitemap | Contact
Latest Visitors: United States's flagUnited States's flagUnited States's flagUnited States's flagKorea  Republic of's flagUnited States's flagUnited States's flagRussian Federation's flagChina's flagSweden's flagNetherlands's flagUnited States's flagUnited States's flagChina's flagChina's flagPakistan's flagUnited States's flagUnited States's flagUnited States's flagSpain's flagUnited States's flagUnited States's flagUnited States's flagUnited States's flagUnited States's flag

Reading Files With JavaScript

Rod Divilbiss
12/14/2006
Updated Library: 07/02/2007
[See Part 2 For Improved Code]

"I'm afraid we have become a nation of plodders, who feel that all problems can be found in books and that the answers are on a certain page."
                                           Clarence Linder

"Now we just use Google"
                                           the Author

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.

Remote scripting, also know as the "HTTP Request Object" has been available to all modern web browsers for several years.. While not a W3Crecommendation, this object is an extension to the browser's DOM specifically written to allow a client side remote call to the server to read a file.  You may be more familiar with this object when used with the term AJAX, or by the objects declarative name in script, XMLHTTP.  To see why remote scripting is an elegant solution we can look at the short-comings of the methods recommended in the past. [see sidebar]

When a developer asks how he may read a file with JavaScript the most common response is, "You can't!" It is technically true that with JavaScript alone you can not read a text file.  Some people will correctly point out that you must also have HTML to use JavaScript so you can load your file into an IFRAME tag. Those people were able to rephrase the question and attempt to understand the problem better before suggesting a solution.  Restated the problem is, "There is no server side method available on the web site to read the file, then what are the client side options?"

An IFRAME isn't a bad idea. It is simple to implement and is cross browser. The IFRAME tag is not depreciated and along with the FRAMESET is available in the latest W3C recommendations for HTML 4.01 and XHTML 1.1.  You can do a lot with an IFRAME but you can not manipulate the contents. If your external file was data written by a console program you would only show the raw data.  Remote scripting does not share this limitation.  In the IFRAME's defense, it is able to include a file from another domain into your web page. The remote scripting object can only read files from the same domain.

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; 

Calling include() With The Onload Event
<body onload="include('http://www.ourdomain.com/path/filename.txt');">

In the example we use 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 function, but are received by a results handling function. The XMLHTTP object is making an asynchronous call. That means we do not know when the results will be returned and that is why there is one function devoted to receiving the results.  Here are the two functions.

Basic Read File Code
function include(pURL) {
    if (window.XMLHttpRequest) { // code for Mozilla, Safari, ** And Now IE 7 **, etc
        xmlhttp=new XMLHttpRequest();
    } else if (window.ActiveXObject) { //IE
        xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
    }
    if (typeof(xmlhttp)=='object') {
        xmlhttp.onreadystatechange=postFileReady;
        xmlhttp.open('GET', pURL, true);
        xmlhttp.send(null);
    }
}

// function to handle asynchronous call
function postFileReady() {
   if (xmlhttp.readyState==4) {
      if (xmlhttp.status==200) {
         document.getElementById('theDivToLoad').innerHTML=xmlhttp.responseText;
      }
   }
}
 

These are quite simple and you could cut and paste the code into your page's JavaScript block.  (At the end of this tutorial you will find better code provided as a JavaScript library file which is easier to use.)  You might note the include() function calls the correct version of the remote scripting object depending on the browser type.  The results handling function is also specified in the include() function.

Since you have access to the results, this method allows you to manipulate the contents of the page before it is displayed.  For example, you could put the contents of a standard .csv file exported from a database into a table or a drop down list.  You could highlight search terms or just display the data raw. The following live example demonstrates some of the possibilities.  Read File and Manipulate

Some developers, possibly being unfamiliar with remote scripting will point out some browser's might have JavaScript disabled. Since the original question was how can this be done in JavaScript, making a post hoc argument against remote scripting is a bit silly. It's hardly a bona fideissue.

Some developers may go so far as to suggest that using remote scripting to read a file is overkill.  I can't see how something so simple can be called overkill.  It uses less lines of code than most image rollover scripts and is considerably more useful than a fancy rollover image button.  The network traffic to read the file from the server is the same no matter how you read the file.  It is even better than server side includes because the data file never has to be manipulated in any way to become part of the DOM and accessible for any client side dynamic interaction.  It is incredibly short sited to say a technology to allow remote files to be read which every modern web browser implements should not be used for what it was design to do.

Besides, we can do it as simply as a Server Side Include...thus.

A JavaScript Include
<script>include('thePage.htm','elementId');</script>

Simply add one line to the head of your page to enable the include function.

Just Add One Line To The Head Section
<script type="text/javascript" src="include.js"></script>

A live example of the simple client side include function is available at the following link. [Live example]

I have learned a lot from code examples left by others. I hope you will learn something from this tutorial.  I hope you have a new way to solve a common problem and you do not need to struggle with barely useful hacks.  If you just need to include a file you can always use the IFRAME but there is no reason not to use the remote scripting client side include.  If you need to manipulate or format the file data then you should use this method.

1 July 2007:  After over 25,000 reads, a couple thousand downloads, and some comment from developers, I have created a more enhanced version:  Reading Files With JavaScript Part 2

JavaScript Source for the Client Side Include function. (New version discussed in Part 2, backwards compatible)


 

Other Remote Scripting Articles By This Author

Please Wait! (Letting the user know an AJAX call is pending)
HTTP communications with a Server
Reading A Web Server's Response Headers


1 W3C - World Wide Web Consortium.  Remote scripting as implemented by XMLHTTP has not made it into W3C DOM recommendations, but is considered ubiquitous, such that recommendations under discussion are considering the affect of remote scripting.  For example the Web Content Accessibility Group working group's discussion of remote scripting and the need for recommendations to ensure it is used in a way that does not have a detrimental affect on accessibility. http://www.w3.org/2005/09/20-wcag-teama-minutes.html
2 Internet Explorer 5 and later, (including MSN and AOL,) Gecko engine browsers, (such as Mozilla, Firefox, Netscape, and Camino,) Opera and Safari.
3 A purist might argue it was written to read XML files, however note that while that was considered an application of the object, it first and foremost includes methods specific to reading any file via an HTTP request.
4 Checking web statistics which separate browsers from crawlers, bots and spiders shows in excess of 98% of the browsers have JavaScript enabled.  It is simply not practical to use the web without JavaScript.  Designing for accessibility and graceful degradation is important and recommended by the author.  Those are NOT the subject of this tutorial nor helpful in answering the original question. When multiple web developers propose a solution to a problem, the ones who claim a non-JavaScript solution always argue it is preferable because JavaScript may be disabled. That is not the practice they follow in their real world development - just an attempt to win an argument.



This Weeks Most Popular Pages Newest Pages