Load Table From XMLHttpRequest response

Load Table From XMLHttpRequest response

toriachttoriacht Posts: 20Questions: 5Answers: 1

Hi,

I have got my basic table proof of concept loading from a data file on page load as follows:
ref: https://datatables.net/forums/discussion/45467/load-simple-json-data-error#latest

get data...

    function getSummaryData(cb_func1) {
        $.ajax({
            url: "data/summary.json",
            success: cb_func1
        });
        console.log(cb_func1)
    }

load data...

   $(document).ready(function () {
        getSummaryData(function (data1) {
//            data1 = JSON.parse(data1)
            var dataarray=new Array();
            dataarray.push(data1);
 

            $('#summaryTable').DataTable({
                data: dataarray,
                "columns": [

I am now dynamically retrieving the data via XMLHttpRequest. I upload some files and get a response...

<script>
   ...
var uploadButton = document.getElementById('upload');
   ...

        // Set up the request.
        var xhr = new XMLHttpRequest();

        //upload files...

   ...
        // Set up a handler for when the request finishes.
        //xhr has all response data
        xhr.onload = function () {
            if (xhr.status === 200) {
                // File(s) uploaded.
                uploadButton.innerHTML = 'Upload';
                console.log("resp: "+xhr); //response is stored/retrievedxhr
                console.log("resptxt: "+xhr.responseText);

            } else {
                alert('An error occurred!');
            }
        };

So instead of

$(document).ready(function () {
        getSummaryData(function (data1) {

I would like to load the response of the upload button / xhr.responseText into the table.

I am suitable perplexed. As per my previous few questions, all help gratefully received.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,141Questions: 26Answers: 4,918

    What is contained in xhr.responseText?

    If its a JSON string then you should be able to build and assign it to the Datatables data parameter as your previous example. Maybe post the output of console.log("resptxt: "+xhr.responseText); so we can better understand what is being returned.

    Kevin

  • toriachttoriacht Posts: 20Questions: 5Answers: 1

    Hi Kevin,

    Thanks again for the reply, I'm sorry I did not explain my question properly. The data is exactly the format as the previous question

    {
        "id": 21,
        "keyonename": "myfile.txt",
        "keytwototal": 22,
        "keythreelocation": 23
    }
    

    And i can load it into datatables as per last solution. Load the JSON into an array and the assign it to data like this....

    $(document).ready(function () {
        getSummaryData(function (data1) {
            var dataarray=new Array();
            dataarray.push(data1);
     
            $('#summaryTable').DataTable({
                data: dataarray,
                "columns": [
    
    

    and getSummaryData looks like this, loading from a file...

    function getSummaryData(cb_func1) {
        $.ajax({
            url: "data/summ.json",
            success: cb_func1
        });
        console.log(cb_func1)
    }
    
    

    This was so that I could figure out how to load the data in this format into datatables, I was loading the data from a file on document.ready(). For the real solution the data will be returned by the XHR response, and I want to populate the table only when this happens. The xhr.responseText is exactly the same format as above.

    Use case is

    1. select file
    2. Post file
    3. Populate table of above format into the summaryTable instead of on document.ready.

    Maybe this is more of a general JS question than a datatables question? I'm confused as to how I can wire the POST , post response and datatables together.

  • kthorngrenkthorngren Posts: 21,141Questions: 26Answers: 4,918

    In this portion of your code you can populate the Datatable:

                if (xhr.status === 200) {
                    // File(s) uploaded.
                    uploadButton.innerHTML = 'Upload';
                    console.log("resp: "+xhr); //response is stored/retrievedxhr
                    console.log("resptxt: "+xhr.responseText);
    

    If this happens once you should be able to init the Datatable just like you previous example but use xhr.responseTex for your data.

    But if the data in the Datatable can change then I would initialize the Datatable without data at the beginning of your script. Only once. Then use clear() to clear the table then rows.add() to add the new data in the above code.

    Hope this makes sense. How you do this depends on you requirements.

    Kevin

  • toriachttoriacht Posts: 20Questions: 5Answers: 1

    Hi Kevin,

    It does make sense. I'm almost there!.

    I cant the response to the reload function... i can print it out to console etc, it is as expected. I retrieve the table. I can clear it and draw it again and it clears...
    But ..when i try and reload the new data the table never updates...no error just no update.

       function reload(newData){
    
            console.log(newData);
            var dataarray= new Array();
            dataarray.push(newData); //put json into array as per initial load so datatales will process
            mytable =$('#summaryTable').DataTable();
            mytable.clear();
            mytable.draw(); //this works :)
            
            mytable.rows.add({
                data: dataarray
                "columns": [
                         {"data": "id"},
                         {"data": "keyonename"},
                         {"data": "keytwototal"},
                         {"data": "keythreelocation"}
                ]
            }).draw(); //this does not..table remains empty
    

    Any idea?

  • kthorngrenkthorngren Posts: 21,141Questions: 26Answers: 4,918
    Answer ✓

    What I meant was you would initialize the Datatable at the beginning of the script, before any function calls, etc. Using this:

    <script>
    var mytable =$('#summaryTable').DataTable({
             "columns": [
                      {"data": "id"},
                      {"data": "keyonename"},
                      {"data": "keytwototal"},
                      {"data": "keythreelocation"}
             ]
    
    });
    
    ..... JS code ......
    
    </script>
    

    In your function do this:

         mytable.clear();      
         mytable.rows.add( dataarray ).draw(); 
    

    Kevin

  • toriachttoriacht Posts: 20Questions: 5Answers: 1

    Hi Kevin,

    Thanks again for your patience and replies.

    The thing that was tripping me up was that when i got basic version working loading from a file i had to remove the line data = JSON.parse(data); that was present in most examples, however when loading 'real' data from a remote server then i needed to put it back in.

    I think I'm more or less down to my last question to get this proj. finished which i'll post in a separate thread.

    Thank you again...

This discussion has been closed.