Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog. You can find information on programming, linux, documentation, tips for code and database optimization, my thoughts and rants, and whatever else I feel like sharing. Feel free to contribute to the blog by posting comments and asking questions.
JavaScript and Ajax

MooTools Table Sorter 0.9.5

Well its been a long weekend and I’m starting to wrap it up. But I couldn’t go to bed without redoing the documentation for my baby the MooTools TableSorter and updating the demo page. The documentation will loosely follow what you see in the demo page.

MooTools Table Sorter

HTML Setup

You’ll need to include 3 files: MooTools 1.2 or higher, the CSS file, and the Table Sorter javascript class. You’ll also want to make sure all the images are there and update the CSS image paths to jive with the location on your web server.

1
2
3
<link rel="stylesheet" media="screen" href="/mootools/table-sorter/table-sorter.css" />
<script type="text/javascript" src="/js/mootools1-2.js"></script>
<script type="text/javascript" src="/mootools/table-sorter/table-sorter.js"></script>

PHP Setup

You’ll want to use the TableSorter php class I included to make things easy one you.

Notice setting the table headers is important. For instance when a user clicks on city the TableSorter will send the ORDER BY stored in the TH Title. This is how your server side code will know what to order by. Reply to this post if you have any questions on the server-side PHP code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
include_once 'TableSorter.class.php';
function returnGeoHtmlTableStr($whereClause='',$startingFromRecord=0,$rowsPerPage=100,$orderBy='city ASC')
{
	mysql_connect('localhost','user','password','database');
	mysql_select_db('database');
 
	$startingFromRecord = (int) $startingFromRecord;
	$rowsPerPage = (int) $rowsPerPage;
 
	$sql = "SELECT 
				count(*) as count 
			FROM 
				cnizz_geo 
 
			$whereClause
 
			";
	$result = mysql_query($sql);
	$countArr = mysql_fetch_assoc($result);
	$totalRows = $countArr['count'];
 
	if($orderBy==''){
		$orderBy='city ASC';
	}
 
	$sql = "SELECT SQL_CALC_FOUND_ROWS
				* 
			FROM 
				cnizz_geo 
 
			$whereClause
 
			ORDER BY 
				$orderBy
			LIMIT 
				$startingFromRecord,$rowsPerPage
			";
	$result = mysql_query($sql);
	$arr = array();
	while($row=mysql_fetch_assoc($result)){
		$arr[]=$row;
	}
 
	$sql = "SELECT FOUND_ROWS() as totalRows";
	$result = mysql_query($sql);
	$foundArr=mysql_fetch_assoc($result);
 
	$str = '
		<table class="DefaultTable" style="width:500px;">
		'.TableSorter::returnMetaStr($startingFromRecord,$rowsPerPage,$foundArr['totalRows'],count($arr),$orderBy).'
		<tr style="background:#FFF;"><td colspan="10" style="height:5px;">&nbsp;</td></tr>
		<tr id="GeoHead" class="DefaultTableHeader">
			<th id="City" title="'.(($orderBy=='city ASC')?'city DESC':'city ASC').'">City</th>
			<th id="State" title="'.(($orderBy=='state ASC')?'state DESC':'state ASC').'">State</th>
			<th id="Abbrev" title="'.(($orderBy=='state_abbrev ASC')?'state_abbrev DESC':'state_abbrev ASC').'">State</th>
			<th id="County" title="'.(($orderBy=='county ASC')?'county DESC':'county ASC').'">County</th>
		</tr>
		';
	$x=1;
 
	foreach($arr as $i)
	{
		if($x%2){
			$class='';
		}
		else{
			$class='zebra';
		}
		$str.= '<tr class="'.$class.'">
							<td><a id="'.$i['city'].'" title="'.stripslashes($i['city_id']).'">'.stripslashes($i['city']).'</a></td>
							<td>'.$i['state'].'</td>
							<td>'.$i['state_abbrev'].'</td>
							<td>'.$i['county'].'</td>
						</tr>';
		$x++;
	}
 
	$str.= '<tr style="background:#FFF;"><td colspan="10" style="height:5px;">&nbsp;</td></tr>';
	$str.=$meta.'</table>';
	return $str;
}

Your Server Side Controller

1
2
3
if($_GET['action']=='returnGeoHtmlTableStr'){
	die(returnGeoHtmlTableStr('',$_GET['start'],$_GET['rows'],$_GET['orderBy']));
}

Now the JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
window.addEvent('domready',function(){
	sorter = new TableSorter({
		request: 'action', 
		action: 'returnGeoHtmlTableStr', 
		destination: 'XhrDump', 
		prev: 'PagePrev', 
		next: 'PageNext', 
		head: 'GeoHead',
		rows: 100,
		defaultStartEndWaitEnabled: 1,
		startWait: '',
		endWait: ''
	});
})

Lets explain this line by line.

  1. request: ‘action’, This is how you name the GET parameter. So in this instance the GET looks like $_GET['action']
  2. action: ‘returnGeoHtmlTableStr’, This is the value of GET parameter defined in step 1, so $_GET['action'] = ‘returnGeoHtmlTableStr’
  3. destination: ‘XhrDump’, This is the element id where TableSorter will write results too
  4. prev: ‘PagePrev’, This is the element that the class will listen on for Previous Page requests.
  5. next: ‘PageNext’, Same as above except it goes to the next page when this element is clicked
  6. head: ‘GeoHead’, This tells the class where to look for all those TH tags, which it uses to do sorts on if a Title is defined on the TH tag.
  7. rows: 100, How many rows should the request return.
  8. page: location.href, Where to send the GET request
  9. method: ‘get’, The type of method (GET or POST). By default the method is get, but you can change it to post.
  10. defaultStartEndWaitEnabled: ’1′, this is set to 1 by default. Setting this to 0 disables the built-in visuals (fades, image etc.) you see when performing a sort.
  11. startWait: ”, empty by default, will do a callback function only if defaultStartEndWaitEnabled is set to 0. This is for doing your own custom visuals.
  12. endWait: ”, empty by default, will do a callback function only if defaultStartEndWaitEnabled is set to 0.

Other cool stuff you can do

You can add additional parameters to the GET request in the form of parameter name => parameter value.

1
sorter.addParameter('zipcode','84101');

You can remove these user-defined parameters by calling removeAllParameters.

1
sorter.removeAllParameters();

You can remove a specific parameter by calling removeParameter.

1
sorter.removeParameter('zipcode');

You can initiate a sort anytime you want by calling sort.

1
sorter.sort();

There are some known issues in IE where the up/down arrows will not appear on sorts. Also the visual-effects are a bit degraded in IE as well. When posting questions or bugs you can use the HTML pre tag and set language=”javascript” to get syntax highlighting (wp-syntax plugin). Just makes things easier for me and other readers. Take a look at the source on my syntax highlighting and you’ll see what I mean.

Please reply to this blog post with any comments, bugs, or questions. Enjoy.

No related posts.

Tags: ,

16 Responses to “MooTools Table Sorter 0.9.5”

  1. James Scott says:

    Looks like the demo page is broken! Thanks for the tutorial.

  2. chris says:

    Thanks for letting me know. I moved hosts last night and looks like I forgot my mootools directory. Oops.

  3. Otto Kovarik says:

    Hello,
    I have a problem with this plugin.

    I join all needed files :

    after that I have :

    window.addEvent('domready', function() {
     
      sorter = new TableSorter({
        request: 'action',
        action: 'returnGeoHtmlTableStr',
        destination: 'workshopList',
        prev: 'PagePrev',
        next: 'PageNext',
        head: 'GeoHead',
        rows: 0,
        startWait: "",
        endWait: ""
      });

    and I get JS error in table-sorter.js on line 54:

    $(this.options.head) is null
    var tr = $(this.options.head).getParent();

    I tried 0.9.5 version and 0.9.6 version too

  4. chris says:

    Hi Otto. In what browser are you experiencing this problem?

  5. Otto Kovarik says:

    It was in last firefox, but I found where was the problem. I have bad some of this ID :

    destination: ‘workshopList’,
    prev: ‘PagePrev’,
    next: ‘PageNext’,
    head: ‘GeoHead’

    So Now its OK.
    But I have problem with anything else :

    When I use some sort, arrow shows before the name, after next click it shows arrow with the oposite direction.
    I thought it should be according to parameter in title (for example “name ASC” arrow up and “name DESC” arrow down).

    Next “cosmtetic problem is, that I have in header some row with colspan=”2″. If I ORDER BY next on right row, it will highlight one of the row before…

    Maybe I dont wrote this clear enough. So when I get to my working PC a send can send you an image with this problem.

    If your script cant solve this. I could try it and send you…

  6. chris says:

    I may have gotten the arrows a bit backwards. That can be fixed in my next release. I never designed this with a colspan in my mind as its main use was for strictly tabular data right out of a database. Can you include some screen shots so I can see what its doing. Thanks.

  7. [...] for reporting bugs and feature requests for the new version. For documentation please refer to the version 0.9.5 post. This documentation is still valid. 0.9.6 just fixes bugs in Internet Explorer 6 and Internet [...]

  8. Otto Kovarik says:

    The problem with colspan is in this :

    cell[cellIndex].addClass(‘focusedColumn’);
    cell[cellIndex].addClass(‘focusedColumn’);

    cellIndex is 2 (because first row has colspan=”2″) and it should be 3

    I solve this for my actual application, but it isnt universal.

    But while I using your script I foun another thing :-)
    I would like to set some callback function, when sort is done..
    In table I have link to delete one record, but if I sort table, events disapear, because current table is deleted and new created…

    Is there any way, how set callback ? something like “onSortFinish”…

  9. chris says:

    That is a good feature request. There should really be a onSortComplete and onSortStart. For events that must be duplicated across multiple elements I usually just put an onclick in the returned data server side, but I will add the functionality you request for next release.

  10. Otto Kovarik says:

    Its good to hear that :-)
    I try to solve it for now, but I look forward to next release.

  11. Guido says:

    Hi Chris,

    Nice table sorter you’ve got. I got one question. In your demo the page doens’t scroll back to the top, but to the top of your menu. I downloaded your files but my demo scrolls back to the top of the page.
    You know what can be wrong?
    Thanks in advance.

    Cheers

  12. chris says:

    Hmm..I assume you mean when you perform a sort it’s not scrolling back to where you want it (like in the demo). It’s possible the files I included from the demo on github download are not up to date. Have you integrated table sorter into your application? Does it work as expected there?

  13. sainsi says:

    first of all, great thanks for this script. It looks great.

    but i had a problem when i tried to follow your exemple.
    There was a error:
    web developer (firefox) sayd “syntax error” on “var TableSorter = new Class({” in “table-sorter.js”.

    after a lot of test, i found the problem, in “table-sorter.js” you start with
    /*

    /*

    description: table sorter

    license: MIT-style

    ………………………………
    provides: [table sorting]

    */

    */

    And there is a comment syntax that close nothing.
    you should put
    /*

    description: table sorter
    license: MIT-style
    ……………………………..
    provides: [table sorting]
    */

    PS: Sorry for my English, but my mother language is french

  14. chris says:

    Thanks sainsi and your english is just fine. I’ll get that fixed asap.

  15. Pascal says:

    Thanks for your work, I use it in an administration panel.
    Is there anyway to have also first and last page link?

    Regards

  16. chris says:

    Thanks. That would be easy to do I just have not developed on this plugin in a while, but I’d like to do another release this year and thats a great idea.

Leave a Reply