I'm am trying to use tablesorter to parse json returned for a php POST request.
The Post request returns the json successfully, however, the tablesorter doesn't function correctly. From what I can tell, only the static table data is taking the tablesorter. The tablesorter is not being applied to the returned JSON data that is being formatted into the table rows.
So basically, what I get is a the filter functionality on the header values that are manually placed in the HTML body. I believe that this is happening because the returned json is not in the DOM when tablesorter is being applied to the table. I thought that placing the tablesorter code after the Jquery php post request would fix this, but still not working.
If the problem tablesorter wont work on the returned data, is my only option then to construct the table in the php, and then return the completed table to the page with a php post?
$.when($.post('../php/load_json.php',{path: dir})).done(
function(data){
var obj = jQuery.parseJSON(data);
var html = '';
for(var i = 0; i < obj.length; i++){
html += '<tr><td>' + obj[i].vala+ '</td><td>' + obj[i].valb+ '</td><td>' + obj[i].valc+ '</td><td>' + obj[i].vald+ '</td><td>' + obj[i].vale+ '</td></tr>';
}
$('#mytable tbody').first().after(html);
$("#mytable ")
.tablesorter({
theme: 'blue',
headerTemplate : '{content} {icon}',
widthFixed: true,
widgets: ['zebra', 'filter']
})
});
<html><body>
<table id="mytable" class="tablesorter">
<thead><tr>
<th>vala</th>
<th>valb</th>
<th>valc</th>
<th>vald</th>
<th>vale</th>
</tr></thead>
<tbody>
</tbody>
</table>
</body></html>
Figured it out.
To do this, you have to first initialize tablesorter on an empty table. Then add the data with the PHP Post.
To add the data, I used the append method instead of the first().after(html);
Once this is done, you need to call the trigger method with update.
Here is the updated code.
$("#mytable ")
.tablesorter({
theme: 'blue',
headerTemplate : '{content} {icon}',
widthFixed: true,
widgets: ['zebra', 'filter']
})
});
$.when($.post('../php/load_json.php',{path: dir})).done(
function(data){
var obj = jQuery.parseJSON(data);
var html = '';
for(var i = 0; i < obj.length; i++){
html += '<tr><td>' + obj[i].vala+ '</td><td>' + obj[i].valb+ '</td><td>' + obj[i].valc+ '</td><td>' + obj[i].vald+ '</td><td>' + obj[i].vale+ '</td></tr>';
}
$("#mytable tbody").append(html);
$("#mytable ").trigger("update");
<html><body>
<table id="mytable" class="tablesorter">
<thead><tr>
<th>vala</th>
<th>valb</th>
<th>valc</th>
<th>vald</th>
<th>vale</th>
</tr></thead>
<tbody>
</tbody>
</table>
</body></html>