Please ensure that the table is empty before reloading data into it

I am facing an issue while binding data from the database. The data is being bound every 5 seconds, however, it does not clear the previous data and keeps accumulating. Instead of displaying just 3 rows when there are 3 in the database, it adds 3 rows every 5 seconds, leading to a buildup of 6-9-12 rows and so on. I want to clear the existing data before loading new data every 5 seconds.

<script type="text/javascript">
        $(document).ready(function () {
            Get();
            setInterval(function () {
                Get() // this will run after every 5 seconds
            }, 5000);
        });

    function Get() {
        $.ajax({
            type: "POST",
            url: "../adminpage/noti.ashx",
            data: {},
            dataType: "json",
            success: function (response) {
                $.each(response, function (index, itemData) {
                    var tr = "<tr>" +
                                  "<td>" + itemData.msg + "</td>" +
                                  "<td>" + itemData.dt + "</td>" +
                                  "</tr>";

                    $("#testTable").find("tbody").append(tr);
                });

                BindTable();
            }
        });
    }
    function BindTable() {

        try {
            $('#testTable thead th').each(function (i) {
                var title = $('#testTable thead th').eq($(this).index()).text();

                if (title != "") {
                    $(this).html('<div style="width:40%;text-align:center;white-space:nowrap">' + title + '</div>');
                }
            });

        }
        catch (e) { }
    }
</script>


<table id="testTable" class="display" cellspacing="0" width="100%">
                                        <thead>
                                            <tr>
                                                <th class="m-list-timeline__text" style="width:70%">msg</th>
                                                <th class="m-list-timeline__time" style="width:30%">dt</th>
                                            </tr>
                                        </thead>
                                          <tbody></tbody>
                                    </table>

Answer №1

To improve the performance of your code, make sure to clear all <tr> nodes from the tbody before appending new results:

success: function (response) {
    $("#testTable").find("tbody").empty(); // clear all content from tbody before appending new data.
    $.each(response, function (index, itemData) {
         /* do something */
         $("#testTable").find("tbody").append(tr);
    });
    BindTable();
}

Answer №2

$('#myTable').empty() 

Prior to making the ajax call, consider clearing the table's content first and then proceed with filling it with data.

Answer №3

<script type="text/javascript">
      $(document).ready(function () {
          fetchData();
           setInterval(function () {
            fetchData() // this function will be called every 5 seconds
            }, 5000);
       });

function fetchData() {
    $.ajax({
        type: "POST",
        url: "../adminpage/noti.ashx",
        data: {},
        dataType: "json",
        success: function (response) {

              // Checking if the response data is not empty 
            if (response) {
              // Clear previous data

                 $("#testTable").empty();
              // Loop through each row of data

                 $.each(response, function (index, itemData) {
                 var row = "<tr>" +
                              "<td>" + itemData.msg + "</td>" +
                              "<td>" + itemData.dt + "</td>" +
                              "</tr>";

                $("#testTable").find("tbody").append(row);
            });

            BindTable();
        }
       }
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method for incorporating information into an existing object when it is currently empty?

When it comes to data removal, my method involves locating the element using findIndex and marking it as a null value in isInArray. However, if no such data exists, how can I add it to an empty element starting from the first one? For instance, if the fi ...

Display information when hovering over a tag

I'm working on adding a feature where hovering over a link will display a tooltip. For reference, here is an example: https://i.stack.imgur.com/K84Wf.png Are there any alternative JavaScript libraries that offer this functionality? (ideally similar ...

Sorting table tbody elements created dynamically with JavaScript on an npm webpack application is not possible with jQuery UI

My JS-built table is populated with data from a JSON file fetched after a request. I want to be able to drag and drop these tbodys and update the JSON file accordingly. To handle sorting, I decided to use jquery-ui. While .sortable() works well for drag a ...

Initiating Internet Explorer using the APTool application for Selenium automation

Have you ever encountered a situation where you needed to open Internet Explorer from the start menu with the right-click option open with *apptool and then navigate to a specific webpage? I wonder, is it possible to automate this process using Selenium W ...

Transitioning images smoothly and responsively with jQuery, creating a beautiful

Hey there! I'm looking for some help with transforming this jQuery effect. Instead of having fixed sized images, I want to set the size in percentage (width:100%; height:auto) so they can be responsive. Any creative ideas or suggestions? <scri ...

Matching list symbols in regular expressions (Angular 2)

I have been attempting to find a solution for matching a list of symbols using regex, but I keep encountering errors in the result. The symbol list includes: !@#$+*{}?<>&’”[]=%^ if (text.match('^[\[\]\!\"\#\ ...

Is it possible for a function to alter the 'this' object in JavaScript?

Referencing the MDN article on this keyword in JavaScript When not in strict mode, 'this' in a function will point to the global object. However, attempting to modify a global variable within a function does not result as expected. Is there an ...

Is there a way to check for invalid string literals within a string?

Looking for a way to test for invalid (unclosed) strings within a given string? This regex might help: /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]* ...

Error: Compilation was unsuccessful due to module not found. Unable to resolve in ReactJS

As I was wrapping up this task, an unexpected error popped up: Module not found: Can't resolve './components/Post' in ./src/pages/index.js I've tried everything to troubleshoot it but no luck. Here's a rundown of my code snippets ...

When utilizing Reactjs, accessing an element by its id becomes challenging when the element is nested within a map() function

Currently, I am encountering an issue related to reactjs. In my scenario, I have a requirement to compare the height of the screen with a specific div to determine its maximum width. The challenge lies in the fact that the particular div I need to analyz ...

Is there a compelling case for implementing Meteor in 2017?

Back in the day, Meteor was expected to revolutionize web development on node by simplifying the process of creating interactive applications. Though I'm not well-versed in its history, it seems like most of the development effort has shifted elsewher ...

Sending a form field through ajax and subsequently submitting it through php

I am currently in the process of customizing a WordPress plugin that utilizes a front-end form powered by ajax/jquery to submit entries to various logs. My goal is to incorporate an extra field, pass its value to the .js file, and submit this additional in ...

How to manage multiple items within a single MUI/React TextField

Recently diving into the world of JS, React, and MUI, I find myself faced with a challenge involving a MUI TextField that is supposed to handle multiple values. For example: 1*10 5*50 13*250 5*50 1*10 3*33.33 4*25 3*33.33 All on a single line. These ...

Bringing in the node-spotify or spotify-web modules to the browser for seamless integration

Has anyone successfully used Spotify's Playlist API in a browser? It seems that the web API only covers metadata, and to access the full API I need to use libspotify. Do I need to set up a Spotify API server myself or use node libraries like node-spot ...

Connect-busboy: The file being piped to the write stream is either empty or incorrect, depending on its type

My current project involves testing a file upload feature using connect-busboy. Interestingly, I have encountered a peculiar issue when uploading PNG files - although the file gets uploaded, the content seems to be incorrect and unable to open. Upon furthe ...

Creating dynamic components with constructor parameters in Angular 9

Having trouble passing a value to the constructor in the component generation code. Check out the original code here: https://stackblitz.com/edit/angular-ivy-tcejuo private addComponent(template: string) { class TemplateComponent { @ViewChild( ...

Positioning the infowindow in Google Maps API v3

Creating a map with various markers, each with its own info window. However, when attempting to display an info window on multiple markers, the position remains fixed at the first clicked marker. What could be causing this issue? <script type="text/jav ...

Using Vue.js to create numerous modal popups

Currently, I am using Vue.JS for a research project at my workplace. My focus right now is mainly on the front-end. I have a table with several entries, and when a row is clicked, I want a modal popup window to display further details about that specific ...

What could be causing my ng-grid footer to refuse to align with the bottom border?

Currently utilizing ng-grid and various AngularJS UI Bootstrap components on my website, I have encountered a recurring issue. By diligently investigating, I have successfully replicated the problem. Access the Plunker demonstration through this link. The ...

Unusual Behavior Observed in JavaScript Map Reduce

var t = [-12, 57, 22, 12, -120, -3]; t.map(Math.abs).reduce(function(current, previousResult) { return Math.min(current, previousResult); }); // returns 3 t.map(Math.abs).reduce(Math.min); // returns NaN I'm puzzled as to why the second variant ...