Utilizing DataTables and Ajax call to refresh table data with Json response

My table is dynamically generated using Thymeleaf and I want to update its contents with jQuery.

    <table class="table table-hover" id="main-table">
        <thead class="thead-inverse">
            <tr>
                <th class="col-md-2 text-center">Network Id</th>
                <th class="col-md-2 text-center">Rep date</th>
                <th class="col-md-2 text-center">Hashrate [KH/s]</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="networkHashrate : ${networkHashrates}" th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'">
                <td class="text-center" id="hashrateId" th:text="${networkHashrate.id}"> Sample id</td>
                <td class="text-center" id="repDate" th:text="${@findAndDisplayDataService.formatDate(networkHashrate.repDate)}">Sample rep-date</td>
                <td class="text-center" id="hashrate" th:text="${@findAndDisplayDataService.formatHashrate(networkHashrate.hashrate)}">Sample hashrate</td>
            </tr>
        </tbody>
    </table>

To refresh the table every 8 seconds, I have created this function:

$(document).ready(function() {
var table = $('#main-table').DataTable({
           ajax: {
                url: '/refresh',
                dataSrc:''

            },
           paging: true,
           lengthChange: false,
           pageLength: 20,
           stateSave: true,
           info: true,
           searching: false,
           "aoColumns": [
             { "orderSequence": [ "asc", "desc" ] },
             { "orderSequence": [ "asc", "desc" ] },
             { "orderSequence": [ "desc", "asc" ] }
           ],
           "order": [[ 0, "asc" ]]
});


setInterval(function(){
table.ajax.reload();
}, 8000);
});

This is the JSON response received:

[{  
  "id":1,
  "repDate":{  
     "offset":{  },
     "nano":880042000,
     "year":2018,
     "monthValue":4,
     "dayOfMonth":25,
     "hour":12,
     "minute":58,
     "second":53,
     "month":"APRIL",
     "dayOfWeek":"WEDNESDAY",
     "dayOfYear":115
  },
  "hashrate":5114926.0
},...more entries
]

Despite following your advice, I am encountering an error message:

Uncaught TypeError: Cannot read property 'reload' of undefined

I also receive a warning popup that says:

Data Tables warning: table id=main-table - Requestem unknown parameter '0' for row 0 column 0. For more information about this error, please see: http://datatables.net/tn/4

EDIT

I have moved the table declaration outside the function but the warning persists.


EDIT 2

Following your instructions, the data now refreshes successfully. However, there are still some issues present.

Firstly, the stateSave: true property no longer works, causing the table to always reset to the first page upon reload.
Secondly, I have lost all styling such as class="text:center" and the on:click functionality originally included in my HTML file.

Answer №1

It's a good practice to declare the table before $(document).ready method like this:


var data_table;
$(document).ready(function() {
  data_table = $('#main-table').DataTable({"serverSide": true, ...})
  setInterval(function(){
     data_table.ajax.reload();
   }, 8000);
})

If you are facing an error with column definition, consider defining columns using the following approach:


 "columnDefs": [
                    {
                        "targets": 0,
                        "data": "id",
                    },
                    {
                        "targets": 1,
                        "data": "repDate",
                    },
                    {
                        "targets": 2,
                        "data": "repDate",
                    }
                ]

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

Error: Attempting to access the 'clipboard' property on an undefined object results in a TypeError when invoking this.$q.electron.clipboard

I'm currently working on incorporating copy to clipboard functionality into my app using Electron. This is the command I am using: methods: { copyToClipboard () { if (process.env.MODE === 'electron') { this.$q.electro ...

Using npm webpack-mix to execute a JavaScript function stored in a separate file

Currently, I am facing a challenge with accessing a function that is defined in the table.js file from within my index.html. Here is a snippet of the code: table.js let table; function set_table(table) { this.table = table; consol ...

I am experiencing issues with the functionality of front-page.php on my WordPress website

Seeking guidance in addressing a web development issue: I have encountered a problem with a website that I am currently working on locally using WordPress. I added the following code to the header.php file: <link rel="stylesheet" type="text/css" href= ...

Creating an HTML structure that limits each li to only contain three div elements can be achieved using React and Underscore.js

To achieve this specific layout, I am looking to utilize only underscore.js functions. Below is the array that I have: var xyz = [{ 'name': 'test' },{ 'name': 'test1' },{ 'name': &ap ...

Is it possible to modify the host header within an Angular app?

I'm experiencing a vulnerability issue and to resolve it, I need to utilize SERVER_NAME instead of the Host header. Is it possible to accomplish this using Angular? ...

Having difficulty requesting an API in Next.js that relies on a backend cookie

1: When a user logs in, I generate a refresh token and create a cookie using 'cookie-parser'. This cookie is then sent to the path '/user/refresh-token' res.cookie('refreshtoken', refreshtoken, { httpOnly: true, ...

What is the best way to showcase a PDF file on a webpage with multiple thumbnails using JavaScript or jQuery?

I recently undertook a project at work that involved displaying multiple PDF thumbnails/images on a webpage. These files were dynamically loaded from a directory on my system. Each thumbnail corresponded to a PDF file stored in a different directory. My g ...

Customizing Axios actions in Vue JS using a variable

I have a form in my Vue component that sends a reservation object to my API for storage. I am exploring the possibility of setting the axios action dynamically based on a variable's value, without duplicating the entire axios function (as both the pos ...

Access Vuex Getters in a separate JavaScript file

Within the file /store/user/getters.js: function getLoggedIn (state) { return state.loggedIn } In a different file, router-auth.js, I attempted to access the value (true or false) of getters.getLoggedIn in the following manner: import user from '.. ...

Navigation buttons that move the user either up or down the page

I am a beginner in programming and I wanted to create two buttons for my webpage. One button should appear when the page is scrolled more than 300px and take the user to the top, while the other button should be displayed immediately and scroll the user to ...

The Mongoose function findbyIdAndRemove is currently not working properly when triggered on the client-side

I have a specific route in my app that uses the mongoose method findByIdAndRemove. Strangely, when I test this route using postman, it successfully deletes documents from my database. However, when I try to call this method from my client-side JavaScript f ...

Is it possible to verify if each value satisfies a condition within a Javascript function?

I am currently working on a project using Vue.js and Laravel where I have a data list named "questions." My goal is to iterate through this list and check if the answer value for each question is not null. If any question has a null answer, I want to preve ...

Is there a way to efficiently load POST data into SimpleXML?

I am facing a challenge in posting XML data from a textarea input to PHP for parsing and generating an output table. Despite trying various methods, none seem to be yielding results. My current approach is as follows: jQuery('#btnRegistrarXML' ...

Failure to trigger custom event on FB pixel

I have installed the FB pixel helper browser plugin and I am confident that the FB pixel is properly implemented, as it is tracking pageviews correctly. However, I am facing an issue where the code for reporting a custom event is not working, even though ...

Element not chosen in Angular version 6

Recently delving into Angular 6, I've been working on setting up form validation within an Angular form. Validation has been successfully implemented, but there's a minor issue with the select box displaying an empty first value. Here is my code ...

Leveraging the power of AJAX to submit forms on a webpage that are dynamically created by PHP

On my page, there are multiple forms that serve as a "like" button for each post. Next to these buttons is a div called "likes$id" where the number of likes is displayed. This allows me to easily update the like count after making an AJAX call. However, I ...

Utilize API to extract data from JSON files and generate a database entry

Looking to create a database using a JSON file, specifically this one: JSON file Utilizing Visual Studio 2015 and MSSQL 2012. I am incorporating options like Entity Framework with MVC and WEB API template. While I want to use LINQ, I'm unsure of the ...

Is it mandatory to employ the spread operator in the process of updating an object while using the useState hook?

Recently delving into hooks, I stumbled upon an insightful passage in the official documentation regarding Using Multiple State Variables: It is noteworthy that updating a state variable in hooks replaces it entirely, as opposed to merging it like in th ...

Learn how to synchronize global packages across multiple computers using npm

After installing several npm global packages on my work computer, I am now looking to synchronize these packages with another device. In a typical project, we utilize a package.json file to keep track of package details, making it easy to install all the ...

How can I reverse a regex replace for sentences starting with a tab in JavaScript?

In order to format the text properly, I need to ensure that all sentences begin with only one Tab [key \t] and remove any additional tabs. input This is aciton Two tab One tabdialog This is aciton Two tab Second tabdialog out ...