How to populate new rows to Footable with use Ajax and footable_redraw

efkan picture efkan · Aug 6, 2014 · Viewed 13.4k times · Source

I'm trying to add records that's come from Ajax as respond. My codes are the following;

Ps: I can see ajax response with alert command properly.

Html codes

<table id="seller-table" class="table" data-filter="#filter" data-page-size="5">
    <thead>
        <tr>
            <th data-toggle="true">ID</th>
            <th>Date</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>

Data as json

 var data = [{"id": 10, "date": "Mon Aug 04 2014 17:00:00"}, 
             {"id": 11, "date": "Tue Aug 05 2014 17:00:00"},
             {"id": 12, "date": "Wed Aug 06 2014 17:00:00"}];

jQuery codes

    $.ajax({
        url : '/bid/find/',
        data: {  },
        success : function(data) {
            $('table tbody').append(data);
            $('table').trigger('footable_redraw');
        },
        error : function(xhr, statusText, error) { 
            alert("Error! Could not retrieve the data.");
        }
    });

Answer

Chris Laskey picture Chris Laskey · Aug 7, 2014

The array of objects returned by the AJAX call has to be converted to HTML elements before they can be added to the table:

$('table').footable();

function create_seller_table_row (item) {
    var row = $('<tr><td>' + item.id + '</td><td>' + item.date + '</td></tr>');
    return row;
}

$.ajax({
    url : '/bid/find/',
    data: {  },
    success : function(data) {
        $.each(data, function(index, item){
            var row = create_seller_table_row(item);
            $('table tbody').append(row);
        });

        $('table').trigger('footable_initialize');
    },
    error : function(xhr, statusText, error) { 
        alert("Error! Could not retrieve the data.");
    }
});

Then use the footable_initialize trigger instead of the footable_redraw one.

Here's a jsfiddle of it in action.