ton1
ton1

Reputation: 7628

jQuery dataTable sort with ajax loaded data

I have several rows that include some lazy loaded data. For instance,

    <table border="1">
      <tr>
          <th>Employee</th><th>Sales</th>
      </tr>
      <tr>
          <td>Michale</td><td>1000</td>
      </tr>
      <tr>
          <td>Kim</td><td id="kimSales"></td>
      </tr>
      <tr>
          <td>John</td><td id="johnSales"></td>
      </tr>
    </table>

The problem is, I have to retrieve some data after page loaded because of some reasons. Let's suppose kimSales is 1500, and johnSales is 2500.

<script>
    $(document).on('ready', function(e){
         $('#kimSales').text(1500);
         $('#johnSales').text(2500);
    })     
</script>

In this situation, I want to sort properly with lazy loaded data. You know, jQuery dataTable has sorting features through click header of columns, like https://datatables.net I couldn't sort these data properly. The sorted data is not ascending, or dsc --- maybe dataTable couldn't recognize after loaded data.

What I tried :

<script>
    $(document).on('ready', function(e){
         $('#kimSales').text(1500);
         $('#johnSales').text(2500);
    })

    table.dataTable(); // not properly working
</script>

Upvotes: 0

Views: 4346

Answers (2)

Gyrocode.com
Gyrocode.com

Reputation: 58880

If you update cell's data BEFORE initializing the table, it should work correctly.

Also you should be initializing the table in ready event handler. For example:

$(document).on('ready', function(e){
     $('#kimSales').text(1500);
     $('#johnSales').text(2500);

     var table = $('#example').DataTable();
});

If you update cell's data AFTER initializing the table, you need to use cell().invalidate() API method and redraw the table.

For example:

$(document).on('ready', function(e){
     var table = $('#example').DataTable();

     $('#kimSales').text(1500);
     table.cell($('#kimSales').closest('td')).invalidate();

     $('#johnSales').text(2500);
     table.cell($('#johnSales').closest('td')).invalidate();

     table.draw();
});

Upvotes: 2

Hrishikesh
Hrishikesh

Reputation: 632

I hope you want to achieve sorting based on the second column. Try this in the table initialization code and with your preferred sorting technique [asc,desc]

 $('table').DataTable( {
        "order": [[ 1, "desc" ]]
    } );

Upvotes: 3

Related Questions