Skip to content Skip to sidebar Skip to footer

How To Load The Data Into Html Table From A Text File

I'm trying to display the upload.txt records into a html table. The upload.txt file is located at this url : http://localhost:3000/upload. When we call this url it will get upload

Solution 1:

You're not trying to read file line by line try this instead:

function populateTable() {

    var tableContent = '';


    $.get( 'http://localhost:3000/upload', function( data ) {

      alert(data);
      //this will split the string into array line by line
      var lineByline = data.split('\n');
        //here we're itraing the array which you've created and printing the values
        $.each(lineByline , function(key,value){
            tableContent += '<tr>';
            tableContent += '<td>' + value + '</td>';
            tableContent += '</tr>';
        });

        $('#tablediv').html(tableContent);
    });
};

For efficiency you can try loading the file in chunks somthing like:

    //telling your ajax to read only some amount of data
    // you have to use this in recursion to get the entire data 
    // just add this before you call $.get(..)
    $.ajaxSetup({ beforeSend : function(xhr) {
       xhr.setRequestHeader("Range", "bytes=0-2800" );
    }});    

Solution 2:

First problem seems to be the ajax request is not able to find the resource. The ajax source URL is missing the file extension. i.e. "http://localhost:3000/upload"

Data is obtained. Your implemented alert pops up with the data once you add the file extension. But he problem seems to be with the $.each loop

You can update your populateTable function with the below one

function populateTable() {

    var tableContent = '';

    $.get('http://localhost:3000/upload.txt', function(data) {
       alert(data);
       $('#tablediv').html(data.replace('n',''));
    });
}; 

Solution 3:

DEMO

I assume you are getting it back as string. Then you need to split the string on based on space character and then loop it and also need to avoid first string which will client_ip

var ips=data.split(' ');
var tableContent;
$.each(ips, function(key,value){
    if(key==0) //do not display client_ip which is first string
        return;
    tableContent += '<tr>';
    tableContent += '<td>' + value + '</td>';
    tableContent += '</tr>';

});
$('table').html(tableContent);

Solution 4:

Some update to my pervious answer

This would handle your requirement to the best

function populateTable() {

    var tableContent = '';


    $.get( 'http://localhost:3000/upload.txt', function( data ) {

      alert(data);
      var lineByline = data.split('\n')
        $.each(lineByline , function(index,value){
            tableContent += '<tr>';
            tableContent += '<td>' + value + '</td>';
            tableContent += '</tr>';
        });


        $('#tablediv').html(tableContent);
    });
};

Post a Comment for "How To Load The Data Into Html Table From A Text File"