Is it possible to populate table by passing JSON array to datatables

Is it possible to populate table by passing JSON array to datatables

kulkarni_ashkulkarni_ash Posts: 35Questions: 8Answers: 0
edited February 2012 in DataTables 1.8
Is it possible to populate datatable by passing JSON array as parameter, for example i have a JSON ajax call which returns me a JSON array data, i would like to populate datatable with this JSON array, i know i can do AJAX call from datatable itself, but i would like to explore this option of getting data first and then building table using this data

Replies

  • allanallan Posts: 63,397Questions: 1Answers: 10,451 Site admin
    It sure is with aaData: http://datatables.net/release-datatables/examples/data_sources/js_array.html

    Allan
  • kulkarni_ashkulkarni_ash Posts: 35Questions: 8Answers: 0
    Thanks
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    what do you mean? Thats a hardcoded array. Wheres the code to actually load json data into datables?
  • allanallan Posts: 63,397Questions: 1Answers: 10,451 Site admin
    What the difference between JSON data and a Javascript object/array? If you want to ajax load it, just call $.ajax. Then you get a javascript object or array that you can give to DataTables.

    Allan
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    tried that. So you are saying just substitute the hardcoded array like so:
    "aaData": jsondata

    Didn't work for me. something else I'm missing?
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    I see that it is loading data into the datatable, but it displays everything as null. It has the correct amount of records and fields, but displays null. Got a popup error message saying "Datatables warning(tableid = 'tblForecastDetails'): Requested unknown parameter '0' from the data source for row 0". It still displays the data but instead of real data, all fields are null, and there are 450 records which is correct.
    any ideas?
  • allanallan Posts: 63,397Questions: 1Answers: 10,451 Site admin
    Can you give me a link please? It sounds like you might want to use mDataProp: http://datatables.net/blog/Extended_data_source_options_with_DataTables

    Allan
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    edited February 2012
    How would I know what 'format' the json data is in? Maybe it's in the wrong format? But, since I used a call like this, it should work. I have no idea what format the json data should be in, and how to guarantee that datatable() likes my json data:

    function testloadsubstations() {
    var serviceUrl = "http://<%=Request.Url.Authority%>" + "/Services/ForecastService.asmx/GetAllFacilities";
    $.get(serviceUrl, function (data) {
    loadForecastDetailsGrid(data);
    }, "json");
    }
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    Hi. I can't post a link as it's behind a firewall, sorry. But, my code is here:

    *****************************************************************************************************

    function testloadsubstations() {
    var serviceUrl = "http://<%=Request.Url.Authority%>" + "/Services/ForecastManagement.asmx/GetAllFacilities";
    $.get(serviceUrl, function (data) {
    loadForecastDetailsGrid(data);
    }, "json");
    }


    function loadForecastDetailsGrid(forecastDetails) {

    if (forecastDetails != null) {
    //alert("Forecast details loaded data!");

    var oTable = $('#tblForecastDetails').dataTable(

    {
    //"sAjaxSource": forecastDetails,
    "aaData": forecastDetails,

    //"fnServerData": forecastDetails,
    "aoColumns": [
    { "sTitle": "col1", width: "2000px" },
    { "sTitle": "col2" },
    { "sTitle": "col3" },
    { "sTitle": "col4" },
    { "sTitle": "col5", "sClass": "center" }

    ],
    "iDisplayLength": 5,
    "aLengthMenu": [[5], [5]],
    "bJQueryUI": true,
    // "sPaginationType": "full_numbers",
    // "sDom": 'T<"clear">lfrtip',
    "oLanguage": {
    "sSearch": "Search table:"
    }
    // ,
    // "zTop": -1
    });


    // new FixedHeader(oTable);
    }
    }


    *****************************************************************************************************

    If I substitute a hardcoded array of data in the "aaData" field, it works perfectly. and, when I trace the jquery code in Visual Studio, forecastDetails is not null, and is a valid array of data of 450 records, and the table displays "1 to 5 of 450 records" but displays "null" in each field. so the data is there, but dattable() doesn't like the format.
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    How would I find the exact format of the json data? In firebug all it shows is this:

    [ Object { Id="1", SN="AAL", Name="A.A. LSub", value="AAL - A.A. LSub"},
    Object { Id="2", SN="BBJ", Name="B.B. JSub", value="BBJ - B.B. JSub"},
    etc....
    ]
    (450 records)
    But, theres some header info that I can't see in firebug, such as number of records (450), etc. Any idea how I can guarantee that I give datatable() correct data?
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    Would I need to use $.parseJSON(forecastDetails); or something like that?
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    Here is my html table:
    Any issues with this?

    ************************************************************************************************************






    asd sdfsdf
    assdfdf
    asdf
    New Value
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    Also, you said "What the difference between JSON data and a Javascript object/array?" Isn't there a big difference? That's what I'm asking you, I need the answer. And, also if I use $.ajax, won't it return the exact same data as $.get ? what do I do with the data to make sure that datatables() likes it?
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    I've also tried to do it this way, but going through each item in the list that I get back from the $.ajax post. but, of course, then it says "0 records in table" as datatable() can't get number of records. so, I should just be ablt to call datatable(jsondata) and it should work, but there is no example with code that I can actually use.

    ************************************************************************************************************
    oTable = $('#tblHistory').dataTable();
    oTable.fnClearTable();

    var lstHistory = data.d;

    $.each(lstHistory, function (index, current) {
    // $('#tblHistory').dataTable().fnAddData([giCount + ".1", giCount + ".2", giCount + ".3", giCount + ".4"]); giCount++; }
    var newNode = $("");
    $(newNode).children("#tablename").html(current.TableName);
    $(newNode).children("#columnname").html(current.ColumnName);
    $(newNode).children("#oldvalue").html(current.OldValue);
    $(newNode).children("#newvalue").html(current.NewValue);
    var changeddate = new Date(parseInt(current.ChangedDateTime.substr(6)));

    $(newNode).children("#changeddatetime").html(changeddate.toString());
    $(newNode).children("#userchangedby").html(current.UserChangedByLoginName);
    $("#tblHistory").append(newNode);
    }); //end each
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    well, still no help from support. I had to do it all myself. The problem is that the format from the .get call is not what datatable() likes, so you have to convert it into a javascript array.
    ([ ["abc"], [1], ["tom"]
    ["def"], [2], ["joe"]
    )

    But, why doesn't that exist anywhere in the documentation? there should be an easy way to do this, but you have to do it yourself. No realworld usable examples anywhere on this site.
  • intrinsicintrinsic Posts: 14Questions: 0Answers: 0
    edited February 2012
    And, I'll post all the code if anyone needs it. I'll post complete code, not just tidbits to confuse everyone.
  • carlcarl Posts: 2Questions: 0Answers: 0
    edited February 2012
    @intrinsic - If you don't mind posting your code I would appreciate it. I am attempting to do the same thing you mentioned and so far have been unsuccessful.

    I just get a blank table when I get the JSON back. So, I am thinking that my JSON must not be correct or the way I am calling the $().dataTable() function with my data.

    My json looks like this:

    [code]
    [[2011080910263048663 , 6318518 , FVB another component title 2, NEW , DEFAULT , /ExtViewer/OMSItem/displayTableExpansion/2011080910263048663+++++], [2011080910313148732 , 6318519 , FVB new fce title, NEW , DEFAULT , /ExtViewer/OMSItem/displayTableExpansion/2011080910313148732+++++], [2011080910213148644 , 6318516 , FVB new package title, NEW , DEFAULT , /ExtViewer/OMSItem/displayTableExpansion/2011080910213148644+++++], [2011080910213148653 , 6318517 , FVB new component title 1, NEW , DEFAULT , /ExtViewer/OMSItem/displayTableExpansion/2011080910213148653+++++], [2011080910413148757 , 6318520 , FVB another fce title, USED , DEFAULT , /ExtViewer/OMSItem/displayTableExpansion/2011080910413148757+++++], [2011080910513148825 , 6318521 , FVB sets are being created, NEW , DEFAULT , /ExtViewer/OMSItem/displayTableExpansion/2011080910513148825+++++], [2011080910513148834 , 6318522 , FVB new related title, NEW , DEFAULT , /ExtViewer/OMSItem/displayTableExpansion/2011080910513148834+++++], [2011080910563148843 , 6318523 , FVB this title is related, NEW , DEFAULT , /ExtViewer/OMSItem/displayTableExpansion/2011080910563148843+++++], [2011080911013148888 , 6205 , Mathematical Economics (edit), NEW , DEFAULT , /ExtViewer/OMSItem/displayTableExpansion/2011080911013148888+++++], [2011080912113249183 , 6318524 , Fee for Order Router, NEW , DEFAULT , /ExtViewer/OMSItem/displayTableExpansion/2011080912113249183+++++]]

    [/code]


    edit: I just noticed I am getting an error as well. Which might have something to do with it ;)
    The id of my table is id="tableid" But, when for some reason I am getting an error stating that tableid is not defined?


    [code]

    <%@ page import="com.fheg.orderrouter.OMSItem" %>















    var baseUrl = "${createLink(controller: 'OMSItem', action: 'displayItemsTable')}"


    function makeAjaxCall(){

    var jsonData = ""
    $.ajax({
    type:"GET",
    url: baseUrl,
    contentType: "application/x-www-form-urlencoded; charset=utf-8",
    dataType:"json",
    async:false,
    // data: "q=" +
    success: function(data){
    // var d = jQuery.parseJSON(data);
    // alert(data[1].totalRecords);
    // alert(data.results[1].description);
    loadDataTable(data)

    },
    error: function(data){
    alert('error')
    }
    })
    }


    $(document).ready(function() {
    makeAjaxCall();
    // $('table_id').dataTable();
    } );






































    function loadDataTable(data){


    var oTable = ${'tableid'}.dataTable({

    "aaData": data,
    "aoColumns": [
    { "sTitle": "ItemId" },
    { "sTitle": "Item" },
    { "sTitle": "Description" },
    { "sTitle": "Class" },
    { "sTitle": "Org. Code" },
    { "sTitle": "URL" }
    ]
    })
    }






    Search:






    Submit










    [/code]


    Thanks for the help!
  • allanallan Posts: 63,397Questions: 1Answers: 10,451 Site admin
    edited February 2012
    Firstly, there are a number of Ajax examples available on this site - all real world, as they are running live: http://datatables.net/examples/ ("Ajax data source" section).

    If you scroll down the page when the table is loaded, you'll see the JSON response from the server, formatted and highlighted to make it readable.

    Also, it doesn't need to be an array of arrays, you can use an array of objects if you wish (again there are example) and this blog post details how to do it: http://datatables.net/blog/Extended_data_source_options_with_DataTables .

    Finally, this introduction to the data sources options ( http://datatables.net/usage/#data_sources ) details some of the requirements, and points to where further information can be found.

    @carl - DataTables is expecting a JSON object with a property called aaData by default. However if you want to just return an array of arrays, you can set sAjaxDataProp to be an empty string.

    Allan
  • carlcarl Posts: 2Questions: 0Answers: 0
    edited February 2012
    @allan Thanks for your response. I was able to figure out what my issue was (kind of).
    Using one of the examples I just copied the entire page into my gsp page and it still didn't work right.
    What I found was that for some reason it didn't like me calling datatable.js and/or jquery js with the tags.

    Once I changed it to using regular tags to point to the js source it worked!


    edit: my mistake :( It wasn't the script tags. I didn't set up the where my table would be built.
This discussion has been closed.