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

Implement the Vue.js @click directive in a location outside of an HTML element

I've set up a link like this: <a href="#" @click="modal=true">Open modal</a> Here's the data setup: export default { data () { return { modal: false } } } Is there a way to trigger the cli ...

Securing child paths in Vue.js

Having trouble protecting child routes from parent routes, facing some issues export default new Router({ routes: [ //frontend routes { {path: 'auth', component: Auth, children: authroutes, beforeEnter: (to, from, n ...

Issues encountered when integrating a shader

I've created a shader and I'm trying to test it on Codepen. Despite having no errors in the console, the shader still isn't working as expected. Can anyone help me figure out what's going wrong? Below is my vertex shader: <script i ...

AJAX list refresh, fetch additional items and tally

Looking for a solution to update the values of listUsernames and numUsernames after adding an item? Check out this scenario: <ul id='usernameList'> <li class='username'>John</li> <li class='username&apo ...

Deleting a row from a table in AngularJS can be accomplished by following these steps

I am having trouble with deleting rows from a table using angularjs. When I try to delete a row, it ends up deleting the previous row instead of the correct one. How can I fix this issue? Please check out the working DEMO Here is the code snippet: < ...

Error encountered in Listings#index with ExecJS RuntimeError

Upon launching my localhost, I encountered an ExecJS error message that has left me puzzled. Any assistance would be greatly appreciated. A Glimpse into My Localhost The issue originates from /.../conektec/app/views/layouts/application.html.erb, specific ...

Python - Extracting page ID from JSON data

{"query":{"normalized":[{"from":"hijab","to":"Hijab"}],"pages":{"68301":{ When working in a Linux environment using Python: >>> data['query']['pages'] {u'68301': {u'extract': u'<p/>"</b>Hi ...

The attempt to run 'readAsBinaryString' on 'FileReader' was unsuccessful. The first parameter is not the expected type 'Blob'

I am currently working on parsing an xls file. You can find the file by clicking on the following link: However, I am encountering an error that says: 'Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of ...

Iterate over multiple form input variables using PHP

When I iterate through Rice form variables on the PHP side, everything functions properly. <input class="rice" type="text" name="rice[]" > <input class="beans" type="text" name="beans[]" > <input class="price" type="text" name="price[]" > ...

Windows Mobile 6 HTTP server designed specifically for smooth and efficient communication

I'm currently facing a challenge with my mobile web app that runs on Opera Mobile 10 using Windows Mobile 6.5 Professional on a Motorola MC9500 device. Unfortunately, IE Mobile 6 doesn't support the required canvas element and sufficient JavaScri ...

Refresh database records

I am currently using grails and I am exploring ways to update my database table utility by selecting values from two drop down menus. These drop down menus are populated with values from the database based on user selections from another drop down menu. My ...

The type 'Data' is lacking the following attributes from its definition

Being a newcomer to Angular 8, I can't figure out why this error is popping up. If you have any suggestions on how to improve the code below, please feel free to share your tips. The error message reads: Type 'Data' is missing the follo ...

Looking to extract nested JSON data and display it in a PHP table with two separate tables arranged similarly to the JSON structure?

From my PHP file, I am trying to retrieve data from a JSON file and display it in tabular form using PHP. However, I'm encountering an error while attempting to retrieve values from the expense table in the JSON file. The specific error message I am ...

Saving JSON data as a field in PostgreSQL using Spring Data JPA

Looking to create a unique table structure with two columns - an ID and a field specifically designed for storing JSON objects, all managed by Spring Data JPA. Consider this example: @Entity @Table(name = "unique_table") public class UniqueTable { @ ...

NodeJs took an unexpected turn

I’m encountering an issue with an http request to forecast.io. When I make a normal request using $.ajax, everything works fine. However, when I try using the ajax-request module, I receive the following output: SyntaxError: Unexpected token u in JSON at ...

Is using float:right making the jquery slide toggle dropdown div (triggered by hover) appear glitchy?

Utilizing jQuery's slidetoggle and hover functions, I have successfully implemented a dropdown feature in my div. Within this div, there is various information displayed including the date, a note counter, and three buttons. The first two are Tumblr ...

Tips for managing onClick code when a user selects "open link in new tab" within a React js environment

How can I ensure that my tracking code runs when a user clicks a button in my React project, even if they open it in a new tab? Is there a solution for this in React JS? Here's a simple example: var Hello = React.createClass({ render: function( ...

Displaying overlay when sidebar menu is expanded

I am working on creating a smooth overlay transition for when the sidebar menu opens and closes. When the overlay is clicked, I want the menu to close. This is what I have so far: $(document).ready(function() { $('#menu-toggle').click(fun ...

What is the reason behind not being able to assign identical names to my SailsJS models and MySQL tables?

Recently diving into Sails JS, I found myself in unfamiliar territory with RESTful APIs. Following the guide, I created a User model to correspond with my existing users table. Adding attributes based on the table's columns was straightforward, and a ...

Experience a login page similar to Google's with a fully functional back button

I'm currently working on a login page that requires the user to enter their username and have it validated before proceeding. Once the username is confirmed as valid, a new input field for password entry should appear. However, I'm facing an issu ...