www.webdeveloper.com
Results 1 to 4 of 4

Thread: Need a simple javascript to read in a text file and get the number from it

  1. #1
    Join Date
    Nov 2009
    Posts
    13

    Need a simple javascript to read in a text file and get the number from it

    Here is what I have that is not reading the file...

    Code:
    function readTextFile()  {
        var reader = new FileReader();  
        reader.readAsText("counter.txt");           // Read the file
            var text = reader.result;   // This is the file contents
            alert(text);
    }
    The alert i get is just "null". Also, it seems to make my page load very slowly. Is there a better script than this?

  2. #2
    Join Date
    Nov 2009
    Posts
    13

    solved...

    Code:
    function readTextFile()  {
         //this will read file and send information to other function
    
           var xmlhttp;
    
           if(window.XMLHttpRequest){
    
               xmlhttp = new XMLHttpRequest();
    
           }
    
           else{
    
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    
           }
    
           xmlhttp.onreadystatechange = function(){
    
               if(xmlhttp.readyState == 4){
    
                 var lines = xmlhttp.responseText;   
    
                 alert(lines);
    
               }
    
    
           }
    
             xmlhttp.open("GET", "counter.txt", true);
             xmlhttp.send();
    
    }

  3. #3
    Join Date
    Mar 2014
    Posts
    2
    readAsText is asyncronious. So you have to create en event to run your alert when fileread is successfuly complete.
    There is the onload event.

    This will work:
    Code:
    function readTextFile()  {
    
          var fileInput = document.getElementById('fileid');
          
          var reader = new FileReader();
          reader.onload = function(e){
            alert(reader.result);
          }
    
          reader.readAsText(fileInput.files[0]);
    }

  4. #4
    Join Date
    Nov 2010
    Posts
    1,090
    nvm...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles