rexkogitans rexkogitans - 5 months ago 28
jQuery Question

JQuery TableSorter reload and sort

I think this question has been posted several times, but I cannot put the answers together. My script produces an HTML/JS site containing a

div
which contains only a
table
. When the function
refreshTbl
is called, it should reload the content of the
div
(this works) and sort the table within the way it was before (does not work). The table should again be sortable (does not work either).

var currentSort;

$(document).ready(
function()
{
$("#tbl1").tablesorter().bind("sortEnd", function(sorter) {
currentSort = sorter.target.config.sortList; } );
}

);

function refreshTbl()
{
$("#divtbl1").load(window.location.pathname + "?tableonly");
$("#tbl1").tablesorter().bind("sortEnd", function(sorter) {
currentSort = sorter.target.config.sortList; } );
$("#tbl1").trigger("sorton", [currentSort]);
}


I also tried

$("tbl1 tbody").load(window.location.pathname + "?tableonly");


and let the script only send the table body (without the preamble and the
tbody
tags). Did not work either.

What is the correct way to do it?

Answer

The issue is that the .load() function is asynchronous. When javascript executes that code, the .load() function is called, then immediately the next statement is executed; but the table doesn't exist yet.

To solve this use the complete callback built into the jQuery .load() function.

Try this code:

var currentSort = [];

function init() {
  $("#tbl1")
    .tablesorter({ sortList: currentSort })
    .bind("sortEnd", function(sorter) {
      currentSort = sorter.target.config.sortList;
    });
}

$(function() 
{ 
  init(); 
});

function refreshTbl()
{
  $("#divtbl1").load(window.location.pathname + "?tableonly", function(response, status, xhr) {
    if (status === "error") {
      console.error("ERROR!", xhr.status, xhr.statusText);
    } else {
      init();
    }
  });
}