I am trying to populate the html table based on socket io received data. I want to show the previous data aswell, and when I am adding row into specific user id table so I want to live update it. and show the data into html table. Below is my code. But it is only showing the data which is coming from socket , not showing the previous records. And whenever I add new data, it shows that data and removes the previous added data.
Here is the code I am using
<div >
<div >
<div >
<div >
<h4 >Invoice List</h4>
</div>
<div >
<div >
<table id="results">
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
function toTable( data ) {
document.getElementById( 'results' ).innerHTML = "<tr><th>COIN</th><th>EXCHANGE</th><th>MARKET</th><th>PRICE</th></tr>";
document.getElementById( 'results' ).innerHTML = "<tr><td>" data.firstname "</td><td>" data.lastName.toUpperCase() "</td></tr>";
}
var socket = io('http://localhost:5001');
socket.on('getinvoices', (data) => {
console.log(data);
toTable(data.doc);
});
});
</script>
I tried the above code but its only adding the data and removing the previous data.
----JSON RESPONSE---
doc : {
billingAddress: "House 130 Street ABC"
city: "California"
country: "United States"
email: "[email protected]"
firstname: "John"
lastName: "doe"
phone: "5418411247"
state: "Oregon"
zipCode: "97230"
_id: "639b28528ae035dfcd5a4612"
}
CodePudding user response:
This line:
document.getElementById( 'results' ).innerHTML = "<tr><th>COIN</th><th>EXCHANGE</th><th>MARKET</th><th>PRICE</th></tr>";
is resettng innerHTML of the table each time you call toTable( data )
.
You should define your table header in your HTML file, and remove this line from toTable( data )
.
CodePudding user response:
function toTable( data ) {
document.getElementById( 'results' ).innerHTML = "<tr><th>COIN</th><th>EXCHANGE</th><th>MARKET</th><th>PRICE</th></tr>";
document.getElementById( 'results' ).innerHTML = "<tr><td>" data.firstname "</td><td>" data.lastName.toUpperCase() "</td></tr>";
}
The problem is that you are resetting the innerHTML value when you use the =
operator to assign it. You have two options:
1° Change the =
assign operator for this =
2° Send the old data in the socket too
The first solution works if you want to persist the old value only 1 time, but with this solution if you reload the page the table will shows only the actual value.
The second solution works if you want to persist the value until the next update happens, but you'll need to store the old value too.
I don't know what do you want exactly but these two solutions will work. The second solution assumes that you have other function to update the value without socket emission (in a normal page load request)