www.webdeveloper.com
Results 1 to 12 of 12

Thread: Load CSV or TXT file into javascript array

  1. #1
    Join Date
    Feb 2010
    Posts
    11

    Question Load CSV or TXT file into javascript array

    Hi guys, I am new at javascript and I want to know if it is possible to load either a CSV file or TXT file into an array. Basically the file gets downloaded from the net and is actually a txt file.

    e.g. ("Heading 1","Heading 2","Heading 3","Heading 4".... and under that is the details "Data 1","Data 2","Data 3","Data 4"....)

    I can easily convert this to a CSV file too.
    The web page will always display the data and that is all.

    At the moment I have this code in my js file which I found on the net after searching for two days, this is the only way I know of at the moment. Is this OK and how do I move it into an array.
    Code:
    	var txtFile = new XMLHttpRequest();
    	        txtFile.open("GET", "file://D:/Notices/notices.txt", true);
    	        txtFile.onreadystatechange = function() {
      		if (txtFile.readyState === 4) {  // Makes sure the document is ready to parse.
        	        if (txtFile.status === 200) {  // Makes sure it's found the file.
        	        allText = txtFile.responseText;
          	        lines = txtFile.responseText.split("\r\n"); // Will separate each line into an array
        		} //"\r\n" 
      	    }
    	}
    Am I going about this correctly? Is there an alternative to do this? I was going to display the information in a table. Bearing in mind that this is to be diplayed on a screen for people to read in a reception area. The text file itself will not have more than 100 lines (max). I will want the information to scroll on the screen but that is another problem for another day. I just need to find a way to display this text file on screen.

    Thanks.

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,354

    Lightbulb Consider this ...

    Assuming the TXT (or CSV) file is loaded into the 'allText' (textarea?) correctly:

    var allTextLines = [];
    allTextLines = allText.split(/\r\n|\n/);
    Should create an array of all the lines from the text loaded

    Then for each line to process:

    var fldHeading = []
    fldHeading = allTextLines[0].split(',');
    Should create an array of the heading information and

    var fldData = []
    fldData = allTextLines[x].split(',');
    Should create an array for each data field
    where 'x' is the array position from 1..n

    Depending upon what you want to populate (table? div? list?)
    you should be able to create the display from the two arrays.

    Note, you might need to do extra processing if the data fields contain a ',' separator WITHIN the field.

    Good Luck!

  3. #3
    Join Date
    Aug 2007
    Location
    Michigan
    Posts
    16
    I am struggling with the same code set. I got the fso.OpenTextFile() method to work but cannot get XMLhttpRequest() working with file:// or with a http:// reference. Eventually I will need to index records but when I cannot even read a single line into a varible .

    I'm hoping to pull a single record out of a table and display in a standardized form. Here is what I've got, what am I missing?

    <script type="text/javascript">
    var allText =[];
    var allTextLines = [];
    var Lines = [];

    var txtFile = new XMLHttpRequest();
    txtFile.open("GET", "file://c:/data.txt", true);
    txtFile.onreadystatechange = function()
    {
    allText = txtFile.responseText}
    allTextLines = allText.split(/\r\n|\n/)
    }

    document.write(allTextLines);<br>
    document.write(allText);<br>
    document.write(txtFile);<br>
    </script>

  4. #4
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,354

    Exclamation

    Ajax code will ONLY work with files on a server. Cannot read local 'files'.

    If you need to load local 'files', then you will need to change the extension to .js and put in valid javascript code.

  5. #5
    Join Date
    Aug 2007
    Location
    Michigan
    Posts
    16
    thanks
    Someone said you could just replace http:// with file:// and PROTON's exampled referenced d:\notices\notices.txt so I tried it as well.
    Found some more step by steps at CreativeCommons.org
    Last edited by ComputerJoe; 03-08-2010 at 06:55 PM.

  6. #6
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,354

    Question

    Quote Originally Posted by ComputerJoe View Post
    thanks
    Someone said you could just replace http:// with file:// and PROTON's exampled referenced d:\notices\notices.txt so I tried it as well.
    Found some more step by steps at CreativeCommons.org
    So ... did it work? If it did, post some referenced as I've read that it is not possible elsewhere.

  7. #7
    Join Date
    Feb 2010
    Posts
    11
    Quote Originally Posted by JMRKER View Post
    So ... did it work? If it did, post some referenced as I've read that it is not possible elsewhere.

    Damn I am having trouble reading the local file. I did get it to work once, but changed the code. I'll be going back and trying to replicate what I did.

  8. #8
    Join Date
    Aug 2007
    Location
    Michigan
    Posts
    16
    I've tried embedding the script in html and referencing server side and local data.txt and still have not received a response with my document.write statements.

    you are further ahead than I.

  9. #9
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,354
    I think you guys are kicking a dead horse.

    The only way to reference a local text file I know of is with ActiveX using MSIE. But this is a one browser solution. I still don't think javascript is able to do Ajax loads that are not from the server.

    But ... let me know if you can prove me wrong ... it would be news for all.

  10. #10
    Join Date
    Feb 2010
    Posts
    11
    OK so far I can get the text to display on the page and this is the code I have at the moment. I am still testing this out.

    Code:
    	
            var allText =[];
    	var allTextLines = [];
    	var Lines = [];
    	var txtFile = new XMLHttpRequest();
    	
    	txtFile.open("GET", "file://D:/Notices/notices2.txt", true);
    	allText = txtFile.responseText;
    	//allTextLines = allText.split(/\r\n|\n/);
    	//alert(allTextLines);
    	txtFile.onreadystatechange = function()
    	{
    		if (txtFile.readyState == 4)
    		{
    			
    				  // Makes sure it's found the file.
        				allText = txtFile.responseText;
    					allTextLines = allText.split(/\r\n|\n/);
    				
    					document.write(allText);
    				} else { //alert("Didn't work"); 
    				}
    		
    		}
    	txtFile.send(null)
    I don't have much time to play around with this, but I will try it this whole week when I have free time. Tell me what you get guys and if you can improve on this. Basically I am glad I got it to display on the page. Now I need to see if I can manipulate the data. And yes I have been reading that opening files in JS is really a no no because security issues. But I just want to display what is in the txt file on screen.

  11. #11
    Join Date
    May 2013
    Posts
    1

    Post Load and parse a CSV file from a server

    Hello,
    I'm facing almost the same problem I want to load a CSV file and parsing it into an array to show it.
    The problem is that I can't even download the file, each time the array stays empty.
    Here is codes that I used : (The code cotted as a comment doesn't work as well)


    Code:
    //function readCSV(locfile) {
    
    // load a whole csv file, and then split it line by line
     //var req = new XMLHttpRequest();
     //req.open("GET",locfile,true);
     //req.send();
     //req.open("POST",locfile,false);
     //req.send("");
     //return req.responseText.split(/\n/g);
     
     //}
     function readCSV(U,V) {
     var csvRequest = new Request({
                        url:U,
                        onSuccess:function(response){
                            //The response text is available in the 'response' variable
                            //Set the value of the textarea with the id 'csvResponse' to the response
                            $("csvResponse").value = response;
                            alert ("Success");
                        }
                    }).send(); //Don't forget to send our request!
                    alert ("Test : "+response);
        return     response;    
        //var X = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
        //X.open(V ? 'PUT' : 'GET', U, false );
        //X.setRequestHeader('Content-Type', 'text/html')
        //X.send(V ? V : '');
        //return X.responseText.split(/\n/g);
    }

  12. #12
    Join Date
    Mar 2009
    Posts
    467
    Maybe I'm not understanding the exact why of it but it seems to me that you ought to be parsing the information files on the server and then spitting it out as a JSON structure. The javascript on the client side can just gulp it down with no processing needed. Use AJAX to call a program on the server that will produce the JSON from the csv or text file.

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