How do I initialize my table AFTER my data is retrieved from my backend?

How do I initialize my table AFTER my data is retrieved from my backend?

ajrcodesajrcodes Posts: 2Questions: 1Answers: 0

Hi all,

This is the second time I've run into this "issue," so I figured I'd make a post to ask for help.

On page load, I want to make a call to a Lambda function, which returns the formatted data for my table to the client.

     data = callLambda()
     $(function () {
        $('#main-table').DataTable( {
          data: data,
          processing: true,
          columns: [
              { title: "Name" },
              { title: "Symbol" },
              { title: "Rank" },
              { title: "Price" },
              { title: "Market Cap" }
          ]
        });
      });

My problem: the table initializes before the call to the Lambda returns, and I get errors/a blank table. I tried structuring my code to utilize callbacks, but I couldn't get it to work!

Last project I ended up throwing in the towel and manually putting a .5 second delay on drawing the table... but that felt like cheating and I'd love to learn how to properly setup my tables with a Lambda backend. If this design is fundamentally flawed, please please please tell me — I'm trying to improve as a developer.

Appreciate all the help you can provide, let me know if you need any other details.

This question has an accepted answers - jump to answer

Answers

  • rf1234rf1234 Posts: 2,956Questions: 87Answers: 416

    You should probably use an event and put your function in there. The "xhr" event seems to be suitable.

    https://datatables.net/reference/event/xhr

    Here is an example from my own coding. I used the debugger a lot to figure out what data tables is really returning from the server. In my example I needed to do something with options read from the server.

    reportTable
    .on('xhr', function( e, settings, json, xhr ) {
        //we need to get the editor drop down options with the selectable filter ids
        if ( json != null ) {
            //json.options["report.report_type_id"] is an array of objects like this:
            //"label" is the label of the filtr plus the rendered field type
            //"value" is the filter's id
    //            serverReportTypeOptions = 
    //            [                    
    //                {label: "00: Darlehensübersicht", value: "50"},
    //                {label: "01: Übersicht Einlagen und Ausleihungen", value: "51"},
    //                {label: "02: Übersicht Derivate", value: "52"},
    //            ];
            if ( typeof json.options !== 'undefined' ) {
                serverReportTypeOptions = json.options["report.report_type_id"];
            }
        }
    })     
    
  • allanallan Posts: 63,331Questions: 1Answers: 10,436 Site admin
    Answer ✓

    How are you calling your lambda function? Are you using $.ajax or something similar? If the DataTable has already been initialised you can use rows.add() to add the data returned from the function.

    Allan

  • ajrcodesajrcodes Posts: 2Questions: 1Answers: 0

    Sorry I'm late getting back to this, was not working on the project. Thanks for the replies.

    While I decided to use an API that utilized my Lambda function, the concept is the same. For others — this was my end code.

      data = []
      var table = $('#main-table').DataTable( {
        data: data,
        processing: true,
        columns: [
            { title: "Name" },
            { title: "Symbol" },
            { title: "Rank" },
            { title: "Price" },
            { title: "Market Cap" }
        ]
      });
    
      $.get("APIURL", function(data, status){
        table.rows.add(data)
        .draw();
      });
    

    QUESTION:
    Is this good practice for a static website? Async call to API, wait for it to return, then populate the DataTable? Or should I try to preload the data before initializing the DataTable?

  • allanallan Posts: 63,331Questions: 1Answers: 10,436 Site admin

    That's fine. You could just use data: [] in the initialisation, rather than needing a variable for the empty array, since you don't actually do anything with it.

    However, you could use DataTables' own ajax for this:

    var table = $('#main-table').DataTable( {
      ajax: {
        url: 'APIURL',
        dataSrc: ''
      },
      processing: true,
      columns: [
          { title: "Name" },
          { title: "Symbol" },
          { title: "Rank" },
          { title: "Price" },
          { title: "Market Cap" }
      ]
    }); 
    

    The ajax.dataSrc option will tell DataTables just to expect an array of data in the JSON, which it appears you are using.

    Allan

This discussion has been closed.