Cannot read property 'length' of undefined while data exists

Cannot read property 'length' of undefined while data exists

nava1021nava1021 Posts: 9Questions: 0Answers: 1
edited June 2016 in Free community support

Hi,

I get Cannot read property 'length' of undefined error message while using datatable. The ajax url successfully fetches the JSON data and columns are mapped correctly as the names obtained from the server.

Here is the returned object

{
    "d": "[{\"title\":\"Basic Price\",\"effectiveDate\":\"2016-06-20\",\"row_id\":8,\"value\":10,\"sector\":\"REAL\",\"fiscalYear\":\"2016/17\",\"remarks\":\"\"}]"
}

However, When I use dataSrc:'' property next to data, the error message goes but nothing is displayed in the datatable.

Here is my code


var DTO = { id: indicatorID, sector: sector }; $('#main_data').dataTable({ ajax: { url: "AddGDP.aspx/GetMainData", type: "POST", contentType: "application/json;", data: function () { return JSON.stringify(DTO); } }, });

debug link : http://debug.datatables.net/uxaqum

Replies

  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin

    I'm not clear why you are trying to stringify a string :-). I think you want to parse it!

    Try:

    data: function ( json ) {
      return JSON.parse( json.d );
    }
    

    Allan

  • nava1021nava1021 Posts: 9Questions: 0Answers: 1
    edited June 2016

    Many Thanks Allan as usual.

    I must admit I forgot to JSON.parse the returned JSON string. I changed the code to the following and voila it worked....

       var DTO = { id: indicatorID, sector: sector };   //query parameters
        $('#main_data').dataTable({
            ajax:
            {
                url: "AddGDP.aspx/GetMainData",                   
                type: "POST",
                contentType: "application/json;",
                data: function () {                        //stringify JSON and send param to server
                    return JSON.stringify(DTO);
                },
                 dataSrc: function (json) {              //receive JSON back from server and parse the string
                   return JSON.parse(json.d);
             },
            },               
        });
    
    

    Thanks for assisting and saving my time and patience

    <3 datatable <3 Allan :smile:

    Nava

  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin

    Oops - yes, ajax.dataSrc! Good to hear you got it working :-)

    Allan

This discussion has been closed.