Reload HTML table after every AJAX call - javascript

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?

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();

You can use jQuery to delete every children of type tr with $("#data_table tr").remove();.
So you'll have something like this:
var data = $('#data_input').val();
var tableRef = document.getElementById('data_table');
$.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);
}
}

Related

how to replace old table rows with new rows using javascript

I have created a dynamic table in html click here to view image the rows are created dynamically in javascript please refer the image click here to view image the data for table is fetched from firebase.
The problem I am facing is that the rows are getting added at the end of the table repeatedly resulting in duplicate rows please refer the image click here to view image how do I remove old rows and add new updated rows using javascript.
I have updated the snapshot.forEach loop with comments.
snapshot.forEach(function (data) {
var val = data.val();
var trow = document.createElement('tr');
var tdata = document.createElement('td');
var tdata1 = document.createElement('td');
tdata.innerHTML = val.Name;
tdata1.innerHTML = val.Votes;
trow.appendChild(tdata);
trow.appendChild(tdata1);
// set the Name as data-id attribute
// which can be used to query the existing row
tdata.setAttribute('data-id', val.Name);
// append the trow to tbdy
// only if there's no row with data-id value of val.Name
// otherwise update the vote column of the existing row
var existingRow = tbdy.querySelector('[data-id="' + val.Name + '"]');
if (!existingRow) {
tbdy.appendChild(trow);
} else {
existingRow.querySelectorAll("td")[1].innerHTML = val.Votes;
}
});

how can i make this ajax code work with any kind of html file

I have a ajax call which will get some data from database and I have to load these into a html file. But, the problem is I have different html files and I do not know the content of html file
I have tried it for around 2-3 days and have searched different ways to append data to a html file.
I have made some changes in the code. please assume that the code is working fine.
thank you.
$.ajax({
type: "GET",
url: "api/dataFromDataBase",
success: function (data) {
tableHead = data[0].split("?");//contains data from database
$("#databaseContent").append("<tr>");
for (var i = 0; i < 80; i++) {
$("#databaseContent").append("<th>" + tableHead[i] + "</th>");
}
$("#tableHeading").append("</tr>");
tableHead += data[0];
$("#FromHtml").append(data[1]);
},
});
in this file #databaseContent is an id in the html, so i can easily append the data. but I have no idea about what the html contains. Is their any way i can append data to it??
If you don't have a point of injection on a successful Ajax call. You can append this entire table at the end of the html page.
// all of this within the success call of the AJAX
var tableHead = data[0].split("?");//contains data from database
var tableEle = document.createElement("table");
var tableBody = document.createElement("tbody");
var tableTr = document.createElement("tr");
for (var i = 0; i < 80; i++) {
var cell = document.createElement("th");
var cellText = document.createTextNode(tableHead[i]);
cell.appendChild(cellText);
row.appendChild(cell);
}
tableBody.appendChild(tableTr);
tableEle.appendChild(tableBody);
document.body.appendChild(tableEle);
What we are trying to do here is, create a table element and within the loop creating the content of the table and at the end we're appending the newly created table to the
"document.body". This should work for all html since all html pages have a body tag.

Param in js function not working

I try to get the row id, on expand row.
$table.on('expand-row.bs.table', function(e, index, row, $detail) {
var res = $("#desc" + index).html();
$detail.html(res);
var table = document.getElementById("actionTable");
var row = table.rows[index];
Cookies.set(row.id, 'show');
alert(row.id)
});
When I try alert(index), the index is shown.
When I try var row = table.rows[1];, alert(row.id) shows me the id of the row (I have 3 rows in the table)
But when I try with var row = table.rows[index];, I am not getting the row id.
I tried with parseInt(), but no success.

Error "Cannot read property 'appendChild' of null at generateTable"

Can someone please shine some light on my this error is tossed? outputTable is properly referenced, and my JS file with the array countries is properly formatted.
I reckon I am appending erroneously, but I have tried all that I can.
PS if youre going to downvote, at least please tell me how to improve my questions in the future. I couldnt find a different question that exists already that matches my issue.
window.onload = generateTable();
function generateTable() {
// get the reference for the body
var outputTable = document.getElementById('outputTable');
// revoke existing Body element
if (outputTable) {
outputTable.removeChild(outputTable);
}
// creates a <tbody> element
var tableBody = document.createElement('tbody');
// creating all table rows
for (var i = 0; i < countries.length; i++) {
// creates a table row
var row = document.createElement('tr');
// create table column for flag
var colFlag = document.createElement('td');
//create image element in flag column
var flag = document.createElement('img');
flag.src = 'flags/' + countries[i].Code.toLowerCase() + '.png';
flag.alt = countries[i].Code;
row.appendChild(colFlag);
//append flag to flag column
colFlag.appendChild(flag);
// create table column for Code
var colCode = document.createElement('td');
//append code to code column
colCode.appendChild(document.createTextNode(countries[i].Code));
row.appendChild(colCode);
// create table column for country //**ENGLISH */
var colCountry = document.createElement('td');
colCountry.appendChild(document.createTextNode(countries[i].Name.English));
row.appendChild(colCountry);
// create table column for continent
var colCont = document.createElement('td');
colCont.appendChild(document.createTextNode(countries[i].Continent));
row.appendChild(colCont);
// create table column for area
var colArea = document.createElement('td');
colArea.appendChild(document.createTextNode(countries[i].AreaInKm2));
row.appendChild(colArea);
// create table column for population
var colPop = document.createElement('td');
colPop.appendChild(document.createTextNode(countries[i].Population));
row.appendChild(colPop);
// create table column for capital of country
var colCap = document.createElement('td');
colCap.appendChild(document.createTextNode(countries[i].Capital));
row.appendChild(colCap);
// attach columns to row
tableBody.appendChild(row);
outputTable.appendChild(tableBody);
}
// add the row to the end of the table body
document.body.appendChild(outputTable);
}

Insert HTML table row with JavaScript with different variable names

I have a page that allows users to edit their data (On the database). I have a JavaScript that inserts rows. Those rows contain textboxes whose values are stored in different variables. So, i need a way to insert a table row that has the same structure, but different variable names.
In order to insert/edit data at the same time, i need different values on different fields. (The insertion/editing is made on the edited.php page)
JavaScript:
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
</script>
This Script inserts a table row on my html table. That insertion is made by copying the first table row. I need a NEW row with NEW variables.
Is there anyway to define the row that is inserted?
You can use the javascript createElement function, here is a little example that should get you on your way:
function addNewRow(tableID) {
var table = document.getElementById(tableID);
var row = document.createElement('tr');
var data = document.createElement('td');
var tbx = document.createElement('input');
tbx.setAttribute('type', 'text');
data.appendChild(tbx);
row.appendChild(data);
table.appendChild(row);
}
it should be fairly self-explanatory, create an element, set its attributes, and add children elements to it, in your case: textbox, checkbox etc.
If you need to have dynamic ids and/or values, add a counter variable and increment as you go along and/or add parameters like
function addNewRow(tableID, input1, input2, input3){}
You can assign the name to each row you create dynamically like this:
var row_counter=0 // have a global counter
var row = table.insertRow(rowCount);
row.setAttribute("id", "row"+row_counter);
//NOW INCREMENT THE COUNTER BASED ON YOUR LOOP
You can work out the loop in a way you want.

Categories