Check for empty JSON result

Check for empty JSON result

tristanvanbokkemtristanvanbokkem Posts: 19Questions: 0Answers: 0
edited February 2013 in General
Hi Allan,

I am using DT with a JSON array as source. However I noticed DT is throwing me an "Cannot read property 'length' of null " if the returning JSON array is empty. When this happens the "Processing..." state keeps loading instead of stating "No data found" or something similar. How can I fix this?

Replies

  • tristanvanbokkemtristanvanbokkem Posts: 19Questions: 0Answers: 0
    I guess, this will help me. http://datatables.net/forums/discussion/1605/empty-json-result/p1
    I'll check if it works for me.
  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin
    Two options currently:

    1. Use fnServerData to override the Ajax call DataTables makes and catch the return, altering it to be an empty array if null.

    2. Listen for the `xhr` event and pre-process the data that way.

    [code]
    $('#table').dataTable().on('xhr', function (settings, json) {
    if ( json.aaData === null ) {
    json.aaData = [];
    }
    } );
    [/code]

    Allan
  • tristanvanbokkemtristanvanbokkem Posts: 19Questions: 0Answers: 0
    Thanks Allan,

    I'm almost there.

    [code]
    "fnServerData" : function(sSource, aoData, fnCallback){
    aoData.push( { "name": "action", "value": "someAction" } );
    $.ajax({
    "url": sSource,
    "data": aoData,
    "success": function(result){
    // DEBUG
    //console.log(result)
    if (result.aaData === null) {
    result.aaData = [];
    }
    // DEBUG
    console.log(result);
    fnCallback // draw the table
    }
    });
    [/code]

    I can see that the result contains:

    [code]
    Object {aaData: Array[0]}
    [/code]

    But the processing state keeps loading.
  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin
    You need to actually call the callback function :-). `fnCallback( result );`

    Allan
  • tristanvanbokkemtristanvanbokkem Posts: 19Questions: 0Answers: 0
    Perfect! Topic can be closed.
This discussion has been closed.