skip to Main Content

I would like to query a JSON via post request from a rest API:

http://localhost/post1  
param1='1'

that returns the following:

{
  "json_table": [
    {
      "date": 123,
      "test": "hello2"
    },
    {
      "date": 19,
      "test": "hello"

    },
}

and it should then be automatcially populated into a jquery datatable, a little bit how it is described here:

$('#myTable').DataTable( {
    ajax: '/api/myData'
} );

What I don’t understand is:

  • How can I tell it to make a post request with a parameter
  • How can I create the table without having to predefine it in HTML, so that it’s completely agnostic what is returned from the JSON and just displays the table accordingly, whatever is within the ‘json_table’ record (which is generated from a pandas data frame df.to_json(orient=’records’)?
  • How can I make it refresh (query again) every 15 seconds and update the table?

Any suggestions are appreciated.

2

Answers


    1. To make the post request with parameters , U can do is:
       $.ajax({
         type: 'POST',
         dataType: "json", #define the response type as Json
         url: url,
         data: data,  # make a post request with a parameter you want
         success: success
       });
    
    1. U can create table with json data like this :
    <script type="text/javascript">
    var myContacts = [{ "name": "Parvez Ansari", "email": "[email protected]", "mobile":"9998979695" },
      { "name": "Tayyeb Shaikh", "email": "[email protected]", "mobile":"9091929394" },
      { "name": "Ashfaque Shaikh", "email": "[email protected]", 
    "mobile":"8081828384" }
    ];
    
    function generateDynamicTable(){
    
        var noOfContacts = myContacts.length;
    
        if(noOfContacts>0){
    
    
            // CREATE DYNAMIC TABLE.
            var table = document.createElement("table");
            table.style.width = '50%';
            table.setAttribute('border', '1');
            table.setAttribute('cellspacing', '0');
            table.setAttribute('cellpadding', '5');
    
            // retrieve column header ('Name', 'Email', and 'Mobile')
    
            var col = []; // define an empty array
            for (var i = 0; i < noOfContacts; i++) {
                for (var key in myContacts[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }
    
            // CREATE TABLE HEAD .
            var tHead = document.createElement("thead");    
    
    
            // CREATE ROW FOR TABLE HEAD .
            var hRow = document.createElement("tr");
    
            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            for (var i = 0; i < col.length; i++) {
                    var th = document.createElement("th");
                    th.innerHTML = col[i];
                    hRow.appendChild(th);
            }
            tHead.appendChild(hRow);
            table.appendChild(tHead);
    
            // CREATE TABLE BODY .
            var tBody = document.createElement("tbody");    
    
            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            for (var i = 0; i < noOfContacts; i++) {
    
                    var bRow = document.createElement("tr"); // CREATE ROW FOR EACH RECORD .
    
    
                    for (var j = 0; j < col.length; j++) {
                        var td = document.createElement("td");
                        td.innerHTML = myContacts[i][col[j]];
                        bRow.appendChild(td);
                    }
                    tBody.appendChild(bRow)
    
            }
            table.appendChild(tBody);   
    
    
            // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
            var divContainer = document.getElementById("myContacts");
            divContainer.innerHTML = "";
            divContainer.appendChild(table);
    
        }   
    }
    </script>
    
    1. U can refer this code for refreshing in every 15 mins :
      Check this Ans
    Login or Signup to reply.
  1. Creating a dynamic DataTable from arbitrary JSON is certainly possible – but it can get complicated depending on how many of the features of DataTables you are trying to use.

    Also, if you have control over the JSON being sent from the server, you can make things easier for yourself. I will assume you do have such control for what follows.

    Static Example

    Assume we start with this simple static example:

    The server sends this JSON data:

    {
      "data": [
        {
          "id": "1",
          "name": "Tiger Nixon",
          "position": "System Architext",
          "salary": "$320,800",
          "start_date": "2011/04/25",
          "office": "Edinburgh",
          "extn": "5421",
          "toggle": "off"
        },
        {
          "id": "2",
          "name": "Garrett Winters",
          "position": "Accountant",
          "salary": "$170,750",
          "start_date": "2011/07/25",
          "office": "Tokyo",
          "extn": "1278",
          "toggle": "on"
        }
      ]
    }
    

    And we have a simple DataTables definition like this:

    <body>
    
    <div style="margin: 20px;">
    
    <table id="example" class="display" style="width:100%"></table>
    
    </div>
    
    <script type="text/javascript">
    
      $(document).ready(function() {
    
        var table = $('#example').DataTable( {
          "ajax": { 
            "url": "http://localhost:7000/employees",
            "dataSrc": "data",
            "type": "GET", 
          },
          "columns": [
            { "data": "name",
              "title": "Name" },
            { "data": "position",
              "title": "Position" },
            { "data": "office",
              "title": "Office" },
            { "data": "extn",
              "title": "Extn." },
            { "data": "start_date",
              "title": "Start Date" },
            { "data": "salary",
              "title": "Salary" },
          ]
    
        } );
    
      } );
    
    </script>
    
    </body>
    

    Enhancing the JSON

    To make things easier for ourselves, we can enhance the JSON being sent from the server, to contain metadata about the columns in the data records:

    {
      "response": [
        {
          "columns": [
            {
              "data": "name",
              "title": "Name"
            },
            {
              "data": "position",
              "title": "Position"
            },
            {
              "data": "office",
              "title": "Office"
            },
            {
              "data": "extn",
              "title": "Extn."
            },
            {
              "data": "start_date",
              "title": "Start Date"
            },
            {
              "data": "salary",
              "title": "Salary"
            }
          ]
        },
        {
          "data": [
            {
              "id": "1",
              "name": "Tiger Nixon",
              "position": "System Architext",
              "salary": "$320,800",
              "start_date": "2011/04/25",
              "office": "Edinburgh",
              "extn": "5421",
              "toggle": "off"
            },
            {
              "id": "2",
              "name": "Garrett Winters",
              "position": "Accountant",
              "salary": "$170,750",
              "start_date": "2011/07/25",
              "office": "Tokyo",
              "extn": "1278",
              "toggle": "on"
            }
          ]
        }
      ]
    }
    

    This new columns section in the JSON is basically the same information as was hard-coded into the first DataTables definition.

    We can read that into a variable, when we receive the JSON from the server, and then use this variable in our DataTables configuration.

    And we can do the same thing for the data records also:

    var tableData = [];
    var tableColumns = [];
    
    ...
    
    $('#example').DataTable( {
      "data": tableData,
      "columns": tableColumns
    } );
    

    For more flexibility, the ajax request can be separated out from DataTables:

    <script type="text/javascript">
    
      var tableData = [];
      var tableColumns = [];
    
      function ajax1() {
        return $.ajax({
          url: "http://localhost:7000/employees",
          success : handleData,
          type: "POST",
          data: { "foo": "bar" }
        });
      }
    
      function handleData(data) {
        tableData = data.response[1].data;
        //console.log(JSON.stringify(tableData));
        tableColumns = data.response[0].columns;
      }
    
      $(document).ready(function() {
    
        $.when(ajax1()).done(function(a1){
          $('#example').DataTable( {
            "data": tableData,
            "columns": tableColumns
          } );
    
        });
    
      } );
    
    </script>
    

    The easiest way to assemble what you need is (I think) to write the hard-coded version of your data table – and then to start replacing pieces with dynamically created variables.

    POST with parameters

    The above ajax example includes these lines:

    type: "POST",            // request type (watch out for CORS!)
    data: { "foo": "bar" }   // request body (form parameters)
    

    This means the ajax request will be a POST and will contain a request body in this case containing foo=bar. You can, of course put whatever you need in there. It’s standard form data. The server would read this data in whatever standard way it uses (e.g. request context form parameters).

    Auto-Refresh

    I haven’t done this myself, but there are solutions documented using setInterval – something like this:

    setInterval( function () {
      console.log("reloading");
    }, 2000 ); // milliseconds
    

    Final note – just to reiterate – this is not going to be able to handle whatever JSON you throw at it. And if you have no control over the JSON structures, then there may well be too many differences from one payload to the next.

    But if you control the JSON and if you want to define more features (e.g. default sorting, hidden columns) then you can start adding those to the JSON as additional metadata items.

    Hope that helps or at least gives you some pointers.

    By the way, there should generally be no need to use code which manipulates the DOM (e.g. building strings of HTML, or manipulating tags). That is counter to how DataTables is designed to work. You should instead be working with the DataTables object itself, wherever possible.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search