Share JSON response among several tables

Share JSON response among several tables

toriachttoriacht Posts: 20Questions: 5Answers: 1

Hi,

I have a complex JSON response of multiple JSON arrays (example at the bottom). Each JSON array within the response will populate a different table. Rather than executing multiple requests for each table, can i execute the request once, store as a "global" variable and share it with all the tables?

So ... the naive implementation would be something like the following:

<script>
    $(document).ready(function() {
        $('#example1').DataTable( {
            "processing": true,
            "ajax": {
                "url": "data/myhouse.json",
                "dataSrc": "myhouse"
            },
            "columns": [
                { "data": "name" },
                { "data": "date" },
                { "data": "amount" },
                { "data": "address" }
            ]
        } );
    } );

</script>

and for table 2

<script>
    $(document).ready(function() {
        $('#example2').DataTable( {
            "processing": true,
            "ajax": {
                "url": "data/myhouse.json",
                "dataSrc": "yourhouse"
            },
            "columns": [
                { "data": "name" },
                { "data": "date" },
                { "data": "amount" },
                { "data": "address" }
            ]
        } );
    } );

</script>

Is there a way to read the url once and save in a variable and then pass this variable as the "url" to each JS script?

The JSON response...

{
    "myhouse": [
        {
            "name": "nameywamey",
            "date": "2018-01-12",
            "amount": 500,
            "address": "mystreet"
            
        },
        {
            "name": "nameywamey",
            "date": "2018-01-11",
            "amount": 3000,
            "address": "mystreet"
            
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 3935,
            "address": "mystreet"
            
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 11,
            "address": "mystreet"
            
        },
        {
            "name": "nameywamey",
            "date": "2018-01-12",
            "amount": 11,
            "address": "mystreet"
            
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 11,
            "address": "mystreet"
        
        }
    
    ],
    "yourhouse": [
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 23,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 21,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 56,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 65,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 56,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-12 08:22:58",
            "amount": 55,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 55,
            "address": "mystreet"
        }
    ],
    "house11": [
        {
            "name": "nameywamey",
            "date": "2018-01-12 16:09:09",
            "amount": 55,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 37,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-11",
            "amount": 48,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 11,
            "address": "mystreet"
        }
    ],
    "house22": [
        {
            "name": "nameywamey",
            "date": "2018-01-11",
            "amount": 11,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-11",
            "amount": 11,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 11,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 11,
            "address": "mystreet"
        }
    ],
    "house51": [
        {
            "name": "nameywamey",
            "date": "2018-01-11",
            "amount": 12,
            "address": "mystreet"
        }
    ],
    "house52": [
        {
            "name": "nameywamey",
            "date": "2018-01-10",
            "amount": 12,
            "address": "mystreet"
        },
        {
            "name": "nameywamey",
            "date": "2018-01-12",
            "amount": 89,
            "address": "mystreet"
        }
    ]
}

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951
    edited October 2017 Answer ✓

    This example should get you started. You can use ajax, outside Datatables, to make one request. Then expand this example to extract the desired objects, store in variables then assign the proper variable to the desired Datatable's data option.

    The example also shows how to dynamically build the columns. You don't need to do that and can keep your column config as is.

    This also shows examples of assigning the row data to a variable the using that variable with the data.
    https://datatables.net/manual/data/#Data-source-types

    Kevin

  • toriachttoriacht Posts: 20Questions: 5Answers: 1

    Hi Kevin,

    Thanks again. I'm nearly there (i think!), it's my lack of JS understanding that's blocking me. I have tried multiple things to same effect. I can see ,by debugging that the getData is retrieving the data but I have yet to successfully populate the table. My current version is like this:


    <script> function getData(cb_func) { $.ajax({ url: "data/myhouse.json", success: cb_func }); } </script>

    and...

    <script>
    
        $(document).ready(function() {
            getData(function( data ) {
                data = JSON.parse(data);
    
                $('#example22').DataTable( {
                    data: data,
                    "columns": [
                        { "data": "name" },
                        { "data": "date" },
                        { "data": "amount" },
                        { "data": "address" }
                    ]
                } );
            });
    
        } );
    
    
    </script>
    
    
  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951

    I think you will need to do something like this:

                $('#example22').DataTable( {
                    data: data.myhouse,
    

    Then for the next table:

                $('#example23').DataTable( {
                    data: data.yourhouse,
    

    That should pull the data from the specific object within the JSON response.

    Kevin

  • toriachttoriacht Posts: 20Questions: 5Answers: 1

    i did try that.... ok, i must have had a mistake elsewhere, i'll try again, thanks...

  • toriachttoriacht Posts: 20Questions: 5Answers: 1

    The problem was the JSON.parse(data) there was no need to do this, works as follows..

        $(document).ready(function() {
            getData(function( data ) {
                //data = JSON.parse(data);
                console.log(data)
    
                $('#example22').DataTable( {
                    data: data.myhouse,
                    "columns": [
                        { "data": "name" },
                        { "data": "date" },
                        { "data": "amount" },
                        { "data": "address" }
                    ]
                } );
            });
    
        } );
    
    
  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951

    You can output the data to the console to see what is being returned, like this:

                data = JSON.parse(data);
                console.log(data);
                $('#example22').DataTable( {
    

    Kevin

  • dccevolutiondccevolution Posts: 13Questions: 3Answers: 0

    Ive just stumbled on this having managed to get mine to work but I am struggling to implement a 30 second interval to reload the Datatables since no AJAX call. IS there a way to do this?

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951

    @dccevolution How are you loading the data?

    Kevin

  • dccevolutiondccevolution Posts: 13Questions: 3Answers: 0
    edited April 2020

    Hi @kthorngren , this is where I have got to so far....Javascript is not a major strength of mine (I am PHP based usually)

    function getData(cb_func) {
      $.ajax({
        url: "data/leagues.json",
        success: cb_func
      });
    }
    
    setInterval(function () {
      cb_func.ajax.reload(); 
    }, 5000);
    
    $(document).ready(function () {
      getData(function (data) {
        data = JSON.parse(data);
        
        $('#league1').DataTable({
        data: data.league1,
          responsive: true,
          order: [
            [3, "asc"]
          ],
          dom: '<if>',
          paging: false,
          "columns": [
              { mData: "position"},
              { mData: "name"},
              { mData: "flag"},
              { mData: "time" }
          ]
        });
      });
    });
    });
    
  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951

    Why don't don't you use the Datatables ajax option? Something like this:

    $(document).ready(function () {
        $('#league1').DataTable({
          ajax: {
            url: "data/leagues.json",
            dataSrc: "league1"
          },
          responsive: true,
          order: [
            [3, "asc"]
          ],
          dom: '<if>',
          paging: false,
          "columns": [
              { mData: "position"},
              { mData: "name"},
              { mData: "flag"},
              { mData: "time" }
          ],
          initComplete: function( settings, json ) {
            setInterval(function () {
              $('#league1').DataTable().ajax.reload();
            }, 5000);      
          }
      });
    });
    

    Note the use of ajax.dataSrc and initComplete to start the setInterval.

    Kevin

  • dccevolutiondccevolution Posts: 13Questions: 3Answers: 0

    @kthorngren - that works a treat and thankyou! I wasnt aware of the dataSrc to filter the JSON.

    Final question - I have 4 tables on the same page all calling for the same JSON. IS there a way to just refresh them all at the same time with the same JSON so I am only getting the file once?

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951

    In that case you will need to use something along the lines of what you started with. I would do something like this:
    http://live.datatables.net/fomunipe/1/edit

    It splits the data between two tables. You will want to look at the following docs:
    - tables()
    - clear()
    - rows.add()
    - draw()

    Kevin

  • dccevolutiondccevolution Posts: 13Questions: 3Answers: 0

    Many thanks @kthorngren - I've got something working but unable to get each table to grab its own data for league1, league2, league3 etc. Presumably data: data.league1 etc for each table wont work?

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951

    I made the assumption that the data source is the same. If different then you will need to update each Datatable individually. Like this:

    http://live.datatables.net/fomunipe/3/edit

    Note the use of global variables table1 and table2.

    Kevin

  • dccevolutiondccevolution Posts: 13Questions: 3Answers: 0
    edited April 2020

    Correct @kthorngren data source is the same for all 4 datatables - they are essentially just extracting/filtering their league from a single JSON which looks like the below.

    I need the tables to show their own League and then refresh every 5 seconds from one single file. Trying to figure out how I tell each table to pull its part of the JSON from the data. Presumably I need a variable defined data.league1, data.league2 etc

    {
    "league1": [
    {
    "position": "1",
    "active": null,
    "name": "Choppers",
    "flag": "5",
    "race": "2",
    "team": "3693.775"
    },
    {
    "position": "2",
    "active": null,
    "name": "Purple Armada",
    "flag": "4",
    "race": "1",
    "team": "3958.907"
    },
    ],
    "league2": [
    {
    "position": "1",
    "active": null,
    "name": "GoTeam",
    "flag": "8",
    "race": "2",
    "team": "3207.111"
    },
    {
    "position": "2",
    "active": null,
    "name": "Black Widows",
    "flag": "7",
    "race": "2",
    "team": "3232.941"
    },
    ],
    "league3": [
    {
    "position": "1",
    "active": null,
    "name": "Warriors",
    "flag": "8",
    "race": "3",
    "team": "3437.103"
    },
    {
    "position": "2",
    "CoffeeClass": null,
    "name": "Reprobates",
    "flag": "6",
    "race": "4",
    "team": "3485.457"
    },
    ],
    "League4": [
    {
    "position": "1",
    "CoffeeClass": null,
    "name": "Chasers",
    "flag": "6",
    "race": "5",
    "team": "3784.294"
    },
    {
    "position": "2",
    "CoffeeClass": null,
    "name": "World Beaters",
    "flag": "8",
    "race": "1",
    "team": "3820.092"
    },
    ]
    }

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951

    Change my example to something like this:

            table1.clear();
            table1.rows.add(data.league1).draw();
            
            table2.clear();
            table2.rows.add(data.league2).draw();
    

    Kevin

  • dccevolutiondccevolution Posts: 13Questions: 3Answers: 0

    That fixed it! Absolutely perfect and thank you sooooo much for your help!

This discussion has been closed.