Consume legacy REST API (map TotalRows to iTotalRecords)

Consume legacy REST API (map TotalRows to iTotalRecords)

nsainaneynsainaney Posts: 2Questions: 0Answers: 0
edited October 2012 in General
I wish to use datatables with an existing REST service that supports paging but has it's own parameters/return values (e.g. iTotalRecords is TotalRows). I can't change the server code as it'll break existing apps.

sAjaxDataProp let's you select the "aaData" field but there doesn't seem to be any equivalent for iTotalRecords etc. Also, the server is expecting the fields pageSize and page for pagination handling.

How do I go about mapping these fields?

"fnServerData": function (sSource, aoData, fnCallback) {
$.getJSON(sSource, aoData, function (json) {
alert(json.TotalRows); <----------- would be a good spot to set the values
fnCallback(json)
})

Replies

  • allanallan Posts: 63,205Questions: 1Answers: 10,415 Site admin
    It would be a good spot to set the values. How about:

    [code]
    json.iTotalRecords = json.TotalRecords;
    [/code]

    right where you have your arrow? :-)

    Allan
  • allanallan Posts: 63,205Questions: 1Answers: 10,415 Site admin
    > Also, the server is expecting the fields pageSize and page for pagination handling.

    Missed that bit. You can use fnServerParams to manipulate what is being sent, or just do it in your fnServerData function since you have that anyway.
  • nsainaneynsainaney Posts: 2Questions: 0Answers: 0
    Managed to figure it out. It's a little ugly but seems to work. First, there's a helper function:
    function findElement(list, itemName) {
    var item = $.grep(list, function (n, i) {
    return n.name == itemName;
    });
    if (item != undefined)
    return item[0];
    };

    then just add the following:

    "fnServerData": function (sSource, aoData, fnCallback) {
    var sEcho = findElement(aoData, 'sEcho').value;
    var iDisplayStart = findElement(aoData, 'iDisplayStart');
    var iDisplayLength = findElement(aoData, 'iDisplayLength');
    iDisplayStart.name = 'page';
    iDisplayStart.value = (iDisplayStart.value / iDisplayLength.value) + 1;
    iDisplayLength.name = 'pageSize';
    $.getJSON(sSource, aoData, function (json) {
    json.iTotalDisplayRecords = json.iTotalRecords = json.TotalRows;
    json.sEcho = sEcho;
    fnCallback(json)
    })
    }
This discussion has been closed.