Filling HTML Table with Javascript - SLOW - javascript

I'm having trouble filling a HTML table with javascript efficiently.
For some background; I have a database with around 270k~ entries. I'm using the Javascript Fetch API to retrieve the rows of the SQL database from flask (i.e. my backend). The data transfer is fast - for example I can get the size of the database in less than a second, so that's not the bottleneck.
However, when I loop over the fetch results and try to fill a HTML table with even 50,000 entries, it takes over 15 seconds and the app locks up.
I have read this could be because I'm reading from the DOM, and that reading from native JS storage would be faster.
Would anyone have suggestions on how to solve this bottleneck?
My functions are below - I'm simply looping over the fetch promise and filling with the info.
async function getDB(){
let x;
console.log('Trying to get the entire database')
const res = await fetch('http://localhost:5000/getDB')
.then(function (response){
return response.json();
}).then(function (data) {
x = data
})
return x
};
function fillData(results){
// Dynamically filling the data...
results.then(
function(value) {
var table = document.getElementById("transactions-table");
let sortable = [];
for(var key in value){
// console.log(key + ": " + value[key]);
sortable.push([key, value[key]])
// console.log(key + )
}
sortable.sort(function(a, b){
return a[1] - b[1];
})
for(var key in value){
var row = table.insertRow(key);
var cell1 = row.insertCell(0); // <th>Id</th>
var cell2 = row.insertCell(1); // <th>Forename</th>
var cell3 = row.insertCell(2); // <th>Surname</th>
var cell4 = row.insertCell(3); // <th>Location</th>
var cell5 = row.insertCell(4); // <th>Amount</th>
cell1.innerHTML = value[key][0]
cell2.innerHTML = value[key][1] // Needs to be an index of the row tuple
cell3.innerHTML = value[key][2] // Needs to be an index of the row tuple
cell4.innerHTML = value[key][3] // Needs to be an index of the row tuple
cell5.innerHTML = value[key][4] // Needs to be an index of the row tuple
// row.style.backgroundColor = "red"
}
var row = table.insertRow(0);
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
var cell4 = row.insertCell(3)
var cell5 = row.insertCell(4)
cell1.innerHTML = "<b>ID</b>"
cell2.innerHTML = "<b>Forename</b>"
cell3.innerHTML = "<b>Surname</b>"
cell4.innerHTML = "<b>Location</b>"
cell5.innerHTML = "<b>Amount</b>"
},
function(error) {
console.log('Oh damn')
console.log(error)
}
)
}
No method I can think of so far.

Related

How to render python dictionary values in Javascript Fetch API (forEach)?

I am trying to render python dictionary values inside a Javascript Fetch API. I tried various ways to do so such as serializing values and using dictionary keys to access the dictionary values. I got no error message but the values I rendered are all "undefined" on my webpage.
Python
def portfolio_position(request):
positions = Portfolio.objects.filter(owner=request.user, off_portfolio=False).order_by('-symbol').values()
return JsonResponse([position for position in positions], safe=False)
Javascript
function load_portfolio_position() {
fetch('/portfolio_position')
.then(response => response.json())
.then(positions => {
console.log(positions);
var table = document.getElementById("portfolio-table");
positions.forEach(position => {
var row = table.insertRow(1);
row.id = `row_${position.symbol}`;
var symbol = row.insertCell(0);
var price = row.insertCell(1);
var change = row.insertCell(2);
var average_cost = row.insertCell(3);
var position = row.insertCell(4);
var pnl = row.insertCell(5);
var pnl_percent = row.insertCell(6);
symbol.innerHTML = `${position.symbol}`;
price.innerHTML = `${position.price}`;
change.innerHTML = `${position.change}`;
var avc = parseFloat(position.cost).toFixed(3);
average_cost.innerHTML = `${avc}`;
position.innerHTML = `${position.position}`;
pnl.innerHTML = `${position.pnl}`;
pnl_percent.innerHTML = `${position.pnl_percent}`;
});
})
}
Appreciate your help!

How to read values from a Firebase Database and store them into an HTML table

I have a Firebase Database that stores two values distance and a timestamp. I'm able to read the distances, but un able to read to more than 1 timestamp at a time.
for (var i = 0; i <= 10; i++) {
ref.child("distance").child(i).once("value").then(function(snapshot) {
test = snapshot.val();
test1 = JSON.stringify(test).replaceAll(/[^a-zA-Z0-9.]/g, "");
myCreateFunction(test1, i+"");
});
ref.child("time").child(i).once("value").then(function(snapshot) {
time1 = snapshot.val();
console.log(time1);
myCreateFunc(time1["0"], i+"");
});
}
function myCreateFunction(test1, i) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell2.id = i;
cell1.innerHTML = test1;
}
function myCreateFunc(time1, i) {
document.getElementById(i).innerHTML = time1;
}
This is a picture of my database
This is the picture of the error that we get on our webpage
I think you are only sending your first element of the array to the HTML create table:
myCreateFunc(time1["0"], i+"");
instead of something like this:
myCreateFunc(time1, i+"");
Let me know if this solved your problem!

Getting information on a JS constructed button on click

Is it possible to get information, such as the id, value, of a button created by a javascript loop? For example, the following code, which creates a button for each line in a table formed by an array of objects?
var table = document.createElement("TABLE");
table.setAttribute("id", "tableOfArray");
var array = [ (a large array of objects here) ];
for (var i = 0; i < array.length; i++)
{
row = table.insertRow(i);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell5 = row.insertCell(4);
cell6 = row.insertCell(5);
cell1.innerHTML = i + 1; //for numbering the table
cell2.innerHTML = array[i].property1;
cell3.innerHTML = array[i].property2;
cell4.innerHTML = array[i].property3;
cell5.innerHTML = array[i].property4;
var button = document.createElement("BUTTON");
var buttonText = document.createTextNode("Remove Line");
button.appendChild(buttonText);
button.setAttribute("id", String(i));
button.setAttribute("value", String(i));
button.setAttribute("onClick", "remove()");
cell6.appendChild(button);
}
function remove()
{
?? //gets the value of the button that was pressed
var buttonValue = ??; //assigns the value of button to the variable
arrayTable = document.getElementById("tableOfArray");
table.deleteRow(buttonValue);
}
Is there a method that can be used to get the id or value of the button in order to perform the remove action?
you can pass the current context by passing this
button.setAttribute("onClick", "remove(this.id)");
function remove(id){
var _id=id;// id of the button;
}
Else you can use the event object
function remove(event){
var _target = event.target;
var _getId = _target.id;
var _getParentTD = _target.parentElement; // will give the td which contain button
var _getParentTR = _target.parentElement.parentElement; // will return tr
}

Pagination in a table with dynamic entries from JSON

I am creating a page which is dynamically fetching entries from a JSON file and is displaying it in the form of table I have written the code to create the table in Java script, but it is fetching all the entries at once. I'm trying to create a pagination with only 10 entries per page and trying to create a sort. Here's the function for creating the table.
function myFunction32()
{
var table = document.getElementById("contentTable");
table.innerHTML = "";
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cell1.innerHTML = "Disk ID";
cell2.innerHTML = "Serial Number";
cell3.innerHTML = "Hypervisor IP";
cell4.innerHTML = "TIER";
cell5.innerHTML = "Total Capacity";
for(var i=0; disk.length;i++)
{
var row = table.insertRow(i+1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cell1.innerHTML = disk[i].disk_id;
cell2.innerHTML = disk[i].disk_serial_id;
cell3.innerHTML = disk[i].hypervisor_ip;
cell4.innerHTML = disk[i].storage_tier;
cell5.innerHTML = disk[i].disk_size +" GiB";
}
I have updated the code to include 10 entries per page, but I am not able to create a new button for next page along with sorting.
I am calling my table in the HTML as follows
<div id="fatal" style="margin-left:20px;margin-right:10px;">
<table id = "contentTable" class="table table-bordered"></table>
</div>
Thanks for any help.
I had this same problem and I solved using jQuery datatable, take a look on my gist https://gist.github.com/dptole/08f090b3cbe00e8ba937. You gonna have to edit and apply to your scenario.
From line 65 to 67 I have a wrapper to return the API endpoint string, without actually requesting it.

Correct the serial numbers of the row after deletion using Javascript only

I have two functions for adding and deleting rows in a table using Javascript:
function addRow() {
//document.getElementById("div_dea").style.display = "none";
document.getElementById("div_orderlist").style.display = "block";
var table = document.getElementById("ordertable");
var rowcount = document.getElementById("ordertable").rows.length;
var row = table.insertRow(rowcount);
row.id="row_"+rowcount;
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
var sel = document.getElementById("select_product_name");
var optiontext = sel.options[sel.selectedIndex].text;
cell1.innerHTML = rowcount;
cell2.innerHTML = optiontext;
cell3.innerHTML = "abc";
}
Delete Row as follows:
function deleteRow(){
var table = document.getElementById("ordertable");
var rowcount = document.getElementById("ordertable").rows.length;
alert("first"+rowcount);
for(var i=1;i<rowcount;i++){
row = table.rows[i];
if(document.getElementById(row.id).style.backgroundColor =="red"){
table.deleteRow(row.rowIndex);
}
}
alert("second"+rowcount);
}
While addRow() I am adding serial numbers as: cell1.innerHTML = rowcount;
I need correct the serial numbers after deletion:
The rows get deleted But alert("second"+rowcount); not even working in deletion. How can correct the serial numbers of row after deletion.
Note: Use JavaScript only
Use this code
function updateRowCount(){
var table = document.getElementById("ordertable");
var rowcountAfterDelete = document.getElementById("ordertable").rows.length;
for(var i=1;i<rowcountAfterDelete;i++){
table.rows[i].cells[0].innerHTML=i;
}}

Categories

Resources