JQuery replaces table rows with new data

I am trying to replace a table with new data that I get through ajax. The first time everything works fine, but then the rows are added instead of replacing, so I get duplicate rows.

Here are some of my codes:

success: function(data){ $("#featured_listing_tbody").children( 'tr:not(:first)' ).remove(); counter= 1; $.each(data, function(i, val){ newPropertyRows += '<tr>'; $.each(val, function(key, info){ var skip = false; if(key == "Id") { Id = info; newPropertyRows += ''; skip = true; } if(key == "thumbs"){ info = '<img width="100px" src=uploads/properties/'+Id+'/thumbs/'+info+' />'; newPropertyRows += '<td class="col'+counter+'"><a href="/featured.php?prop='+Id+'">'+info+'</a></td>'; skip = true; counter++; } if(skip == false){ newPropertyRows += '<td class="col'+counter+'"><a href="/featured.php?prop='+Id+'">'+info+'</a></td>'; counter++; } info = ''; }); newPropertyRows += '</tr>'; }); $("#featured_listing_tbody").html(newPropertyRows); } 
+4
source share
3 answers

The problem is probably not in the part of the code you posted. For example, in the current code the += operation is always used with the newPropertyRows variable. Are you reset to delete a line before each ajax call?

By the way, it seems to me that you are not calling $("#featured_listing_tbody").children( 'tr:not(:first)' ).remove() at the beginning of the success handler, because later you use $("#featured_listing_tbody").html(newPropertyRows); which will overwrite the entire table element.

+2
source

I have a suggestion, instead of returning a data object and converting it to HTML in javascript, just return the data as necessary table rows. Since you are already creating them for the page, you must have a logic / template to make this easy again.

To replace the data, I would simply add a <tbody> around your rows of data, and in your ajax success function just replace its contents - instead of making a complex selector to omit the first row of the table, which I assume you are a column heading.

 $("#featured_listing tbody").html(data); //Replace contents of <tbody> tag 

And the table:

 <table> <thead><tr>....row headers...</tr></thead> <tbody>...data rows...</tbody> </table> 
+2
source

Not quite sure if you save the record for the table or if it is in real time and not stored anywhere.

But if it is stored, you can try to create html for the entire table or just rows on the server side, and then just replace the contents of the container / table with the data received from the server.

+1
source

Source: https://habr.com/ru/post/1345539/


All Articles