Friday, 22 February 2008

Sort table rows using Ajax

Simple sort script using Stuart Langridge's sortabe.js

Some days ago I was looking for a good and simple way to sort data into a table with a simple click on table headers and I found this interesting framework: Stuart Langridge's sorttable.js.

This tutorial explains how to use it in your projects:


Download this tutorial (include sorttable.js)

Step 1: include sorttable.js
Create a new page and include in the <head> tag a link to sorttable.js:

<script src="sorttable.js" type="text/javascript"></script>

Step 2: HTML code to design a sortable table
Create a new table and add "sortable" in the table class parameter:

<table class="sortable"> ... </table>

If, in the same page, you have more than one table, you can apply this class to all tables you want to sort. The general structure for each table you want to sort contains a <thead> (table header) a <tbody> (table body) and <tfooter> (table footer) like the following example:

<table class="sortable">
<!-- Table Header -->
<thead>
<tr>
<th>Company</th>
<th>Ticker</th>
</tr>

</thead>

<!-- Tabel body-->
<tbody>
<tr>
<td>Apple Inc</td>
<td>AAPL</td>
</tr>

<tr>
<td>GoogleInc</td>
<td>GOOG</td>
</tr>
</tbody>

<!-- Tabel footer-->
<tfoot>
<tr>
<td>Total</td>
<td> 00.00</td>
</tr>
</tfoot>
</table>

When you click on a header (in this simple example "Company" or "Ticker") all rows within <tbody> tag will be sort in ascending or decreasing order.

Step 3: populate table rows with data using PHP
You can populate a table with some data using a server-side language such as PHP, Coldfusion, ASP or similar. If you use PHP you can use this simple code:

<?php
// Include connection to your database
include('dbconnection.php');
$getCompany_sql = 'SELECT * FROM COMPANY';
$getCompany= mysql_query($getCompany_sql);?>

<table class="sortable">
<!-- Table Header -->
<thead>
<tr>
<th>Company</th>
<th>Ticker</th>
</tr>

</thead>

<!-- Tabel body-->
<tbody>
<?php while ($row = mysql_fetch_array($getCompany)) {?>
<tr>
<th><?php echo $row.['companyName'] ?></th>
<th><?php echo $row.['companyTicker'] ?></th>
</tr>

<?php } ?>
</tbody>

<!-- Tabel footer-->
<tfoot>
<tr>
<td> ... </td>
<td>.... </td>
</tr>
</tfoot>
</table>

Download this tutorial (include sorttable.js)


Related contet
Table's anatomy: why tables are not so bad

No comments:

Post a Comment