Add Rows from json (modified with ajax) to an already initialized table

Add Rows from json (modified with ajax) to an already initialized table

gburns53gburns53 Posts: 8Questions: 2Answers: 0
edited September 2018 in Free community support

I can't seem to find a good example of this on the web. I'm not sure what I'm doing wrong.

The code executes without error. Note my code decides whether the datable exists, if it does, I want to use Rows.Add, but the json may have more columns than table, so I want to pick them. The initialize works fine. Running local PHP server (is this the issue?)

function TTable(str){
    str = 'json/' + str + '.json';

    if (document.getElementById('TTable') != null) {
        var dataTbl = $('#TTable').DataTable();
        
        var data1 = $.ajax({
            type: 'POST',
            url: str,
            contentType: "application/json; charset=utf-8",
            datasrc: function (json) {
                  var return_data = new Array();
                  for(var i=0;i< json.length; i++){
                    return_data.push({
                      'user': json[i].user,
                      'date': json[i].date,
                      'tweet': json[i].string
                    })
                  }
                  return return_data;
                },
            columns: [{data: 'user'}, {data: 'date'}, {data: 'string'}] 
            });
        dataTbl.rows.add(data1).draw(false);
    } else {
    
        document.getElementById('result').innerHTML = "<Table ID='TTable'></Table>"

        $('#TTable').DataTable( {
            ajax: str,  
            columns: [
            { data: 'user' },
            { data: 'date' },
            { data: 'string' }]
        });
    }
}

Json like:
{
[{
"user": "DetroitSteele",
"date": "9/17/2016 3:32",
"string": "Beautiful day for 30 miles on a bike. #tourdetroit @TourdeTroitpic.twitter.com/EwVIZIo4du",
},
{
"user": "DetroitSteele",
"date": "9/14/2016 4:22",
"string": "@adamcarolla I totally misread the plot of The Hammer. At least they didn't spell your name wrong.pic.twitter.com/rjdlHNOx0T",
}]
}

This question has an accepted answers - jump to answer

Answers

  • gburns53gburns53 Posts: 8Questions: 2Answers: 0

    BTW, my json is valid. It was copy/paste method used.
    {
    "data": [{
    "user": "DetroitSteele",
    "date": "9/17/2016 3:32",
    "string": "Beautiful day for 30 miles on a bike. #tourdetroit @TourdeTroitpic.twitter.com/EwVIZIo4du"
    },
    {
    "user": "DetroitSteele",
    "date": "3/8/2014 12:25",
    "string": "Nothing makes me appreciate shopping online more than spending 5+ minutes in a mall"
    }
    ]
    }

  • kthorngrenkthorngren Posts: 20,401Questions: 26Answers: 4,787

    Your example is a bit confusing to me so my answer might be off base. Your return_data variable looks like it has the objects user, date, tweet where everything else has user, date, string. If you use rows.add() with those objects I would expect that you would get this error Requested unknown parameter complaining there is no string object.

    You are using jQuery's ajax function and it doesn't have a datasrc option. However there is a Datatables ajax.dataaSrc option. Instead of datasrc I think you want to use success. So the datasrc function is not executing.

    More info here:
    http://api.jquery.com/jquery.ajax/

    Last, in your jQuery ajax function if the JSON response is the same as your last post then you will need to loop through json.data not just json. When using the success function you will need to use JSON.parse to convert the json parameter to a Javascript variable.

    This example may help:
    http://live.datatables.net/huyexejo/1/edit

    Kevin

  • gburns53gburns53 Posts: 8Questions: 2Answers: 0
    edited September 2018

    Thanks for the example, unfortunately it is one of 100's of examples of adding data to a table that is not yet Initialized. This table is already initialized and needs appended data. I can't seem to find a complete example using Rows.Add (I assume) from a .json source file.

  • kthorngrenkthorngren Posts: 20,401Questions: 26Answers: 4,787
    Answer ✓

    unfortunately it is one of 100's of examples of adding data to a table that is not yet Initialized

    Honestly it doesn't matter whether data exists in the table or not. Adding using rows.add() is the same either way. But here is an example of an ajax initialized table. Click the Get Data button and it will execute an ajax request fetching, in this case, the same data. The JSON response is parsed into Javascript and the data added via rows.add(). You will see duplicated data after clicking the button.

    http://live.datatables.net/lemoruke/1/edit

    Kevin

  • gburns53gburns53 Posts: 8Questions: 2Answers: 0
    edited September 2018

    I got it to work. Just took a long time. I Just didn't understand how to feed the data from Ajax request. I'm a hack:

    function TTable(str){
        
        if (document.getElementById('TTable') != null) {
            var data = []
            data = $.ajax({url: str, dataType: 'json', columns: [{ data: 'user' },{ data: 'date' },{ data: 'tweet' }]});
            var table = $('#TTable').DataTable();
            $.ajax({
                url: 'json/' + str + '.json',
                data: {
                    json: JSON.stringify(str)
                },
                type: "POST",
                timeout: 30000,
                dataType: "json", // "xml", "json"
                success: function(logs) {
                    //myTable.clear();
                    $.each(logs, function(index, value) {
                        table.rows.add(value);
                    });
                    table.draw();
                },
                error: function(jqXHR, textStatus, ex) {
                    alert(textStatus + "," + ex + "," + jqXHR.responseText);
                }
            });
            //table.rows.add(data).draw();
        } else {
        
        document.getElementById('result').innerHTML = "<Table ID='TTable'></Table>"
    
        $('#TTable').DataTable( {
            ajax: 'json/' + str + '.json',  
            columns: [
            { data: 'user' },
            { data: 'date' },
            { data: 'tweet' }]
        });
        }
    }
    
  • gburns53gburns53 Posts: 8Questions: 2Answers: 0
    edited September 2018

    The issue was adding rows from an Ajax request where the table exists. It is hard to find an example. Almost always the ajax example is done during initialization.

    Your 2nd example is good, but it doesn't work for me. I get Syntax Error: "Unexpected token o in JSON at position 1" when I use JSON.parse and implement it in the manner of your example.

This discussion has been closed.