Reputation: 1
I am having problems with sorting an JSON/Ajax generated table. The tablesorter i use is this: https://github.com/Mottie/tablesorter and it works fine when I create tables and content directly in HTML.
This is the code on my index.php:
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="tablesorter master/js/jquery.tablesorter.js"></script>
</head>
<body>
include 'purchases.php';
<div id='id01'></div>
<script type="text/javascript" language="javascript">
//$(document).ready(function() {
//call the tablesorter plugin
$("#myTable").tablesorter();
$("#myTable").trigger("update");
}
);
</script>
</body>
</html>
This is my purchases.php:
<script>
var xmlhttp = new XMLHttpRequest();
var url = "purchasesDB.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
document.getElementById("id01").innerHTML = "";
var arr = JSON.parse(response);
var i;
var out = "<table cellspacing='1' class='sortable' id='myTable'><thead><tr><th>Company</th><th>Amount</th><th>Margin</th><th>Date</th><th>Date 2</th><th>Customer</th><th>Transaction phase</th></tr></thead><tbody>";
for(i = 0; i < arr.length; i++) {
var aTT = arr[i].Id;
out += "<tr><td><a href='index.php?purch=" + aTT + "&p=Purchased'>" +
arr[i].Company +
"</a></td><td>" +
arr[i].Amount +
"</td><td>" +
arr[i].Margin +
"</td><td>" +
arr[i].Date +
"</td><td>" +
arr[i].Date2 +
"</td><td>" +
arr[i].Customer +
"</td><td>" +
arr[i].TransactionPhase +
"</td></tr>";
}
out += "</tbody></table>";
//out += "</tbody></table>";
document.getElementById("id01").innerHTML = out;
}
</script>
The purchasesDB.php is a JSON response and everything works fine except the sorting, which doesn't work at all. What I can see, the potential problems are:
I have tried to put the -tags directly in the HTML code on the index page, but this makes no difference.
Anyone got an idea? As you understand I'm pretty new to this.
Thanks a lot!
Peter
Upvotes: 0
Views: 812
Reputation: 337560
You need to initialise the tablesorter
plugin after the table has been added to the DOM. To do this, move $("#myTable").tablesorter();
to after the innerHTML = out
line.
Upvotes: 1