Search code examples
javascriptjquerytablesorter

Sort ajax data in table with tablesorter.js


I'm trying to use tablesorter.js but im running into issues when using ajax to update my table. I followed the code on this page but it doesn't seem to be working properly. One thing i also notice is that the code doesnt work properly even on the example website. When i click "append new table data" it adds the data to the table but it isn't sorting it correctly. If i copy the javascript code and paste it into the console, it works fine and sorts the table correctly. The code im using is the following:

var updateTableSort = function(){
    var table = $('#transaction-table')
    //tells table sorter that table has been updated
    table.trigger("update");
    //re sorts after table has been updated based on 
   //current sort patern
    var sorting=table.get(0).config.sortList;
    table.trigger('sorton', [sorting]);
}    

Again, if i copy and past this into console it works fine, but when i have it in my success ajax function, it doesnt sort the table properly. Any help figuring out what the issue is would be greatly appreciated


Solution

  • Try my fork of tablesorter. It automatically resorts the table after an update:

    // pass anything BUT false and the table will resort
    // using the current sort
    $("table").trigger("update", [false]);
    

    Here is the updated append data to the table using ajax demo:

    $(function() {
    
      $("table").tablesorter({ theme : 'blue' });
    
      $("#ajax-append").click(function() {
    
        $.get("assets/ajax-content.html", function(html) {
    
          // append the "ajax'd" data to the table body
          $("table tbody").append(html);
    
          // let the plugin know that we made a update
          // the resort flag set to anything BUT false (no quotes) will
          // trigger an automatic
          // table resort using the current sort
          var resort = true;
          $("table").trigger("update", [resort]);
    
          // triggering the "update" function will resort the table using the
          // current sort; since version 2.0.14
          // use the following code to change the sort; set sorting column and
          // direction, this will sort on the first and third column
          // var sorting = [[2,1],[0,0]];
          // $("table").trigger("sorton", [sorting]);
        });
    
        return false;
      });
    
    });