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

Encountering a value accessor error when attempting to test a simple form in Angular 4 and Ionic 3

My ionic form is quite simple: <ion-header> <ion-navbar> <ion-title>Foo</ion-title> </ion-navbar> </ion-header> <ion-content padding> <form [formGroup]="fooForm"> <ion-item> ...

How to use puppeteer to extract images from HTML that have alt attributes

<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 nopadding text-center"><!-- Start Product Photo --><div class="row"><img src="/products/ca/downloads/images/54631.jpg" alt="Product image 1">&l ...

JavaScript allows for selecting individual IDs by their corresponding numbers

Looking to retrieve numerical IDs <div class="user-view"> <div class="show_user_div"> <div class="disp"> <a href="/profile/name1/">name1</a><br /> <span id="show_a_3"> <a id="ref_show(3)">Show Details</ ...

What is the most effective method for invoking an inherited method (via 'props') in ReactJS?

From my understanding, there are two primary methods for calling an inherited method on ReactJS, but I am unsure which one to use or what the best practice is. class ParentCont extends React.Component { constructor(props) { super(props); t ...

Converting an Array with Key-Value pairs to a JSON object using JavaScript

After using JSON.stringify() on an array in JavaScript, the resulting data appears as follows: [ { "typeOfLoan":"Home" }, { "typeOfResidency":"Primary" }, { "downPayment":"5%" }, { "stage":"Just Looki ...

Inquiry on Improving Performance with jQuery

This is the layout of my HTML structure on a page, with an AJAX response that mirrors the same structure: <div id="feeds"> <div class="items"> <div class="feedClass"> content </div> <div c ...

Looking to retrieve the image source from a SQL database and display it in a view file using Ajax in CodeIgniter?

I am new to PHP and have successfully created an AJAX dynamic dependent dropdown in CodeIgniter. It is working fine, but now I want to show an image for the selected option when the last dropdown's option is selected. Please help me with this. View a ...

Tips on extracting JSON information in JavaScript when the key name is unspecified

I have a challenge in parsing JSON data where the property name is unknown. Below is a snippet of my code, and I need your help in figuring out how to retrieve all data with an unknown property. datas.data.videoGroup.past, then utilize a loop $.each(data ...

How to troubleshoot WordPress Ajax function not getting form data

I am currently working on a form in my plugin where I need to send data to my AJAX action function using the standard WP Ajax techniques. Here is the basic structure of my form: <form role="form" id="signup_widget_form" method="post" action="#"> ...

A method for automatically collapsing one div item when another is open

I have tried various methods but none seem to work. I am attempting to open only one div at a time, please click on the link above to see for yourself. Please provide any alternate solutions or suggestions. JsFiddle: http://jsfiddle.net/gm2k3ewp/ < ...

Error Encountered when Button is Clicked in ASP.NET Webforms: Null Reference Exception

I have developed an online testing web application. The website is functioning perfectly on my local machine, but encountering an error when deployed on the remote server. protected void Page_Load(object sender, EventArgs e) { arrSessionALL_ ...

retrieving old information using ajax click function

I'm currently developing a website that utilizes what I believe to be AJAX functionality. The goal is to allow users to input data into a text field, click an "OK" button, save the data to a database, and then reload the text field and "OK" button alo ...

Encountered a NetworkError: 500 Internal Server Error while attempting to request JSON on the hosting

Having an issue with my ASP.NET MVC app. The app uses the FullCalendar jQuery with events requested in a JSON array. The jQueryCalendar code is as follows: function renderCalendar() { $("#cal").fullCalendar({ header: { left: ' ...

Guide on how to bypass IDM when downloading a PDF file through a GET request

When I try to fetch a PDF by sending a GET request to the server and open it in a new tab, IDM interrupts my request and downloads the file instead. It changes the server response status to 204 and removes the headers. How can I prevent IDM from doing th ...

Angular - Implementing an Object Mapping Feature

Looking to dynamically generate parameter objects in Angular with a structure like this: [ password: {type: 'String', required: true, value: 'apassword'}, someRandomParam: {type: 'Integer', required: false, value:3} ] ...

Is there a way to prevent the omission of zeros at the end in JavaScript when using Number.toString(2)?

I am facing an issue while trying to reverse a 32-bit unsigned integer by converting it to a string first. The toString(2) function is causing the zeros at the end to be omitted, leading to incorrect output. This is my code: var reverseBits = function(n) ...

Using JavaScript to retrieve the updated timestamp of a file

Can JavaScript be used to retrieve the modified timestamp of a file? I am populating a webpage with data from a JSON file using JavaScript, and I want to display the timestamp of that file. Is there a way to do this using only JavaScript? ...

Angular - Electron interface fails to reflect updated model changes

Whenever I click on a field that allows me to choose a folder from an electron dialog, the dialog opens up and I am able to select the desired folder. However, after clicking okay, even though the folder path is saved in my model, it does not immediately s ...

Is there a script available on this page that allows me to access the Google Chrome plug-in variable?

Could you kindly clarify if a script on the webpage is able to access variables from a Chrome extension? I have developed an extension for Google Chrome and am concerned about the possibility of the website owner where the extension is running being able ...

Is it better to Angularize Symfony or Symfonyize Angular for Ajax?

When dealing with Ajax, it seems that Symfony (v. 2.7) and AngularJS (v. 1.4) may not be the best match ;-) I have identified two possible solutions to make them work together - my inquiry is: Which one is more effective? Adjust AngularJS to be compatib ...