DataTables logo DataTables

Is it possible to populate table by passing JSON array to datatables
  • 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
  • what do you mean? Thats a hardcoded array. Wheres the code to actually load json data into datables?
  • 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
  • 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?
  • 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?
  • 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
  • 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");
    }
  • 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.
  • 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?
  • Would I need to use $.parseJSON(forecastDetails); or something like that?
  • Here is my html table:
    Any issues with this?

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

    <table id="tblForecastDetails" class="display" cellspacing="0" cellpadding="0" border="0" style=" margin: 5px 25px 0px 0px; color:#000000; border: 1px solid #222222;">
    <asp:Repeater ID="rptForecastDetailsList" Visible="true" runat="server" EnableViewState="false">
    <HeaderTemplate>
    <thead>
    <tr>
    <th class="sorting_asc" width="37%" rowspan="1" colspan="1" style="width: 200px;">asd sdfsdf</th>
    <th class="sorting_asc" width="9%" rowspan="1" colspan="1" style="width: 20px;">assdfdf</th>
    <th class="sorting" width="9%" rowspan="1" colspan="1" style="width: 20px;">asdf</th>
    <th class="sorting" width="9%" rowspan="1" colspan="1" style="width: 20px;">New Value</th>
    </tr>
    </thead>
    <tbody>
    </HeaderTemplate>
    <ItemTemplate>
    <td id="tablename" style="text-align:center;"></td>
    <td id="columnname" style="text-align:center;" class="sorting_1"></td>
    <td id="oldvalue"></td>
    <td id="newvalue"></td>
    </ItemTemplate>
    <FooterTemplate>
    </tbody>
    </FooterTemplate>
    </asp:Repeater>
    </table>
  • 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?
  • 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 = $("<tr><td id='tablename' style='text-align:center;'></td><td id='columnname' style='text-align:center;' class=' sorting_1'></td><td id='oldvalue'></td><td id='newvalue'></td><td id='changeddatetime' style='text-align:center;'></td><td id='userchangedby' style='text-align:center;'></td></tr>");
    $(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
  • 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.
  • And, I'll post all the code if anyone needs it. I'll post complete code, not just tidbits to confuse everyone.
  • @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:

      
    [[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+++++]]
    
    


    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?


    
    <%@ page import="com.fheg.orderrouter.OMSItem" %>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <meta name="layout" content="main" />
            <g:set var="entityName" value="${message(code: 'OMSItem.label', default: 'Item')}" />
            <title><g:message code="or.item.alias.list" /></title>
    
    
            <g:javascript src="DataTables-1.9.0/media/js/jquery.js"/>
            <g:javascript src="DataTables-1.9.0/media/js/jquery.dataTable.js"/>
            <g:javascript src="order_router.js" />
    
    
        <script type="text/javascript">
    
            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();
            } );
        </script>
        </head>
        <body >
            <div class="nav">
                <span class="menuButton"><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></span>
            </div>
            <div class="body">
    
    
    
    
       <table id="tableid">
        <thead>
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
    
        </tbody>
    </table>
    
    
                <script type="text/javascript">
    
            function loadDataTable(data){
    
    
               var oTable = ${'tableid'}.dataTable({
    
                   "aaData": data,
                    "aoColumns": [
                     { "sTitle": "ItemId" },
                     { "sTitle": "Item" },
                     { "sTitle": "Description" },
                     { "sTitle": "Class" },
                     { "sTitle": "Org. Code" },
                     { "sTitle": "URL" }
                    ]
               })
            }
                </script>
    
    
    
                 <div id="searchArea">
    
                     <h3 class="searchHeading">Search: </h3>
                     <span><g:select id="selList" name="selListTypeId" onchange="setQueryLength(this)" from="${searchList}" value="aliasName" noSelection="['0':'--Select--']"></g:select></span>
    
                        <div id="searchTools">
    
                            <input class="searchBox styleBox" type="text" style="width:250px; height:25px;padding-top: .5em" id="querySearch" name="querySearch"  />
    
                             <a class="button medium blue" href="#" onclick="buildJsonTable()" ><span>Submit</span></a>
    
                        </div>
                </div>
    
              </div>
        </body>
    
    
    </html>
    
    


    Thanks for the help!
  • 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
  • @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 <g:javasxcript> tags.

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


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

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Support

Get useful and friendly help straight from the source.