Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Data From Datatables.net after sorting

I'm using Datatables to display some data. I also have inputs that are used to add a new row to the data. When I add this row, I reinitialise the table, and it automatically sorts the new row according to the sorting rules I give it. My question is this: Is there a way to get the data from the table in the order it's currently being viewed? Whenever I try $('#tableCompetitors').dataTable().fnGetData(), it gives me the data in the order it was added to the table not the ordered it's being presented in.

So is there an easy way to do what I want?

P.S. If it helps. The original datasource is an array of arrays that is provided from a textbox. I parse it, push it to an array, then use that array as the datasource.

like image 550
Frank B Avatar asked Feb 12 '13 01:02

Frank B


2 Answers

I came across this with the same question. While the accepted solution may work, I found a better way:

$("example").DataTable().rows({search:'applied'}).data()

See selector-modifier documentation for more information.

like image 55
jonson Avatar answered Sep 29 '22 15:09

jonson


Here is one solution using 3 of the API callbacks.

  1. Create variable for CurrentData
  2. Reset CurrentData to empty array within fnPreDrawCallback which fires before the new table is rendered
  3. fnRowCallback gives access to array of data for each row, push that array into CurrentData array
  4. fnDrawCallback fires after table rendered, can now access sorted data in CurrentData array

JS

  var currData = [];
  $('#example').dataTable({
    "fnPreDrawCallback": function(oSettings) {
        /* reset currData before each draw*/
        currData = [];
    },
    "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        /* push this row of data to currData array*/
        currData.push(aData);

    },
    "fnDrawCallback": function(oSettings) {
        /* can now access sorted data array*/
        console.log(currData)
    }
});

DEMO: http://jsfiddle.net/ne24B/

like image 33
charlietfl Avatar answered Sep 29 '22 14:09

charlietfl