zwiebl zwiebl - 19 days ago 5
HTML Question

Reload HTML table after every AJAX call

My sequential AJAX calls keep appending rows to my HTML table, which I don't want. I want my table to be refreshed/reload on every call with new data, and not appended.

My Code:

var data = $('#data_input').val();
var tableRef = document.getElementById('data_table');

$.getJSON("/data/"+data, function(dataState)
{
// ...
for(var dataId in dataState)
{
var row = document.createElement("tr");
// creating new cells in a row with the data
tableRef.appendChild(row);
}
}


So I'm fetching the reference to my HTML table with
var tableRef = document.getElementById('data_table');
, in the
for
-loop, I'm creating rows and appending them to the HTML table with
tableRef.appendChild(row);
. The problem is that on any sequent
$.getJSON
call, the table gets further appended. How do I refresh my table on every call, ie. delete data from the previous call, and fill data from a new call?

Answer

You can delete the rows after getting the data from the server

$.getJSON("/data/"+data, function(dataState) {

   $("#data_table tr").remove();
       //...

        for(var dataId in dataState) {


                var row = document.createElement("tr");

               // creating new cells in a row with the data

                tableRef.appendChild(row);
            }

        }

    });

Note that it will also remove the headers of the table, if you want to remove the data only and keep the headers, you only remove the rows inside tbody tag i.e $("#data_table tbody tr").remove();

Comments