Yahoo! Developer Network Home - Help

YDN Site Search

# YUI Library Examples: DataTable Control (beta): Server-side Pagination and Sorting, with Browser History Manager

# DataTable Control (beta): Server-side Pagination and Sorting, with Browser History Manager

This example combines server-side pagination and sorting with the Browser History Manager for managing states.

View example in new window.

## Sample Code for this Example

Data:

{"recordsReturned":25, "totalRecords":1397, "startIndex":0, "sort":null, "dir":"asc", "records":[ {"id":"0", "name":"xmlqoyzgmykrphvyiz", "date":"13-Sep-2002", "price":"8370", "number":"8056", "address":"qdfbc", "company":"taufrid", "desc":"pppzhfhcdqcvbirw", "age":"5512", "title":"zticbcd", "phone":"hvdkltabshgakjqmfrvxo", "email":"eodnqepua", "zip":"eodnqepua", "country":"pdibxicpqipbsgnxyjumsza"}, ... ] }

CSS:

/* custom styles for this example */ #dt-pag-nav { margin:1em; } /* custom pagination UI */

Markup:

<div id="dt-pag-nav"> <span id="prevLink"><</span> Showing items <span id="startIndex">0</span> - <span id="endIndex">24</span> <span id="ofTotal"></span> <span id="nextLink">></span> </div> <div id="serverpagination"></div>

JavaScript:

YAHOO.util.Event.addListener(window, "load", function() { YAHOO.example.ServerIntegration = new function() { // Function to return initial config values, // which could be the default set, or parsed from a bookmarked state this.getInitialConfig = function() { // Parse bookmarked state var tmpHash = {}; if(location.hash.substring(1).length > 0) { var sBookmark = location.hash.substring(1); sBookmark = sBookmark.substring(sBookmark.indexOf("=")+1); var aPairs = sBookmark.split("&"); for(var i=0; i<aPairs.length; i++) { var sPair = aPairs[i]; if(sPair.indexOf("=") > 0) { var n = sPair.indexOf("="); var sParam = aPairs[i].substring(0,n); var sValue = aPairs[i].substring(n+1); tmpHash[sParam] = sValue; } } } // Validate values var newResults = parseInt(tmpHash["results"],10); if(!YAHOO.lang.isNumber(newResults)) { newResults = 25; } var newStart = parseInt(tmpHash["startIndex"],10); if(!YAHOO.lang.isValue(newStart)) { newStart = 0; } var newSort = tmpHash["sort"]; if(!YAHOO.lang.isValue(newSort)) { newSort = "id"; } var newDir = tmpHash["dir"]; if(!YAHOO.lang.isValue(newDir)) { newDir = "asc"; } return { paginator: { rowsThisPage: newResults, startRecordIndex: newStart }, sortedBy: { key: newSort, dir: newDir }, initialRequest: "results="+newResults+"&startIndex="+newStart+"&sort="+newSort+"&dir="+newDir }; }; this.initialConfig = this.getInitialConfig(); this.myBookmarkedState = YAHOO.util.History.getBookmarkedState("myDataTable"); this.myInitialState = this.myBookmarkedState || ("results=" + this.initialConfig.paginator.rowsThisPage + "&startIndex=" + this.initialConfig.paginator.startRecordIndex + "&sort=" + this.initialConfig.sortedBy.key + "&dir=" + this.initialConfig.sortedBy.dir); this.myBookmarkHandler = function(newBookmark) { var oSelf = YAHOO.example.ServerIntegration; oSelf.myDataSource.sendRequest(newBookmark, oSelf.myDataTable.onDataReturnInitializeTable, oSelf.myDataTable); }; YAHOO.util.History.register("myDataTable", this.myInitialState, this.myBookmarkHandler); YAHOO.util.History.initialize(); YAHOO.util.History.onLoadEvent.subscribe(function() { // Column definitions var myColumnDefs = [ {key:"id", label:"ID", sortable:true}, {key:"name", label:"Name", sortable:true}, {key:"date", label:"Date", sortable:true}, {key:"price", label:"Price", sortable:true}, {key:"number", label:"Number", sortable:true}, {key:"address", label:"Address", sortable:true}, {key:"company", label:"Company", sortable:true}, {key:"desc", label:"Description", sortable:true}, {key:"age", label:"Age", sortable:true}, {key:"title", label:"Title", sortable:true}, {key:"phone", label:"Phone", sortable:true}, {key:"email", label:"Email", sortable:true}, {key:"zip", label:"Zip", sortable:true}, {key:"country", label:"Country", sortable:true} ]; // Instantiate DataSource this.myDataSource = new YAHOO.util.DataSource("assets/php/json_proxy.php?"); this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON; this.myDataSource.responseSchema = { resultsList: "records", fields: ["id","name","date","price","number","address","company","desc","age","title","phone","email","zip","country"] }; // Instantiate DataTable this.myDataTable = new YAHOO.widget.DataTable("serverintegration", myColumnDefs, this.myDataSource, this.initialConfig); // Custom code to parse the raw server data for Paginator values and page links and sort UI this.myDataSource.doBeforeCallback = function(oRequest, oRawResponse, oParsedResponse) { var oSelf = YAHOO.example.ServerIntegration; var oDataTable = oSelf.myDataTable; var oRawResponse = oRawResponse.parseJSON(); //JSON.parse(oRawResponse); var recordsReturned = oRawResponse.recordsReturned; var startIndex = oRawResponse.startIndex; var endIndex = startIndex + recordsReturned -1; var totalRecords = oRawResponse.totalRecords; var sort = oRawResponse.sort; var dir = oRawResponse.dir; // Update the DataTable Paginator with new values var newPag = { recordsReturned: recordsReturned, startRecordIndex: startIndex, endIndex: endIndex, totalResults: totalRecords } oDataTable.updatePaginator(newPag); // Update the links UI YAHOO.util.Dom.get("prevLink").innerHTML = (startIndex === 0) ? "<" : "<a href=\"#previous\" alt=\"Show previous items\"><</a>" ; YAHOO.util.Dom.get("nextLink").innerHTML = (endIndex >= totalRecords) ? ">" : "<a href=\"#next\" alt=\"Show next items\">></a>"; YAHOO.util.Dom.get("startIndex").innerHTML = startIndex; YAHOO.util.Dom.get("endIndex").innerHTML = endIndex; YAHOO.util.Dom.get("ofTotal").innerHTML = " of " + totalRecords; // Update the config sortedBy with new values var newSortedBy = { key: sort, dir: dir } oDataTable.set("sortedBy", newSortedBy); return oParsedResponse; }; // Hook up custom pagination this.getPage = function(nStartRecordIndex, nResults) { // If a new value is not passed in // use the old value if(!YAHOO.lang.isValue(nResults)) { nResults = this.myDataTable.get("paginator").totalRecords; } // Invalid value if(!YAHOO.lang.isValue(nStartRecordIndex)) { return; } var oSortedBy = this.myDataTable.get("sortedBy"); var newBookmark = "startIndex=" + nStartRecordIndex + "&results=" + nResults + "&sort=" + oSortedBy.key + "&dir=" + oSortedBy.dir ; YAHOO.util.History.navigate("myDataTable", newBookmark); }; this.getPreviousPage = function(e) { YAHOO.util.Event.stopEvent(e); // Already at first page if(this.myDataTable.get("paginator").startRecordIndex === 0) { return; } var newStartRecordIndex = this.myDataTable.get("paginator").startRecordIndex - this.myDataTable.get("paginator").rowsThisPage; this.getPage(newStartRecordIndex); }; this.getNextPage = function(e) { YAHOO.util.Event.stopEvent(e); // Already at last page if(this.myDataTable.get("paginator").startRecordIndex + this.myDataTable.get("paginator").rowsThispage >= this.myDataTable.get("paginator").totalRecords) { return; } var newStartRecordIndex = (this.myDataTable.get("paginator").startRecordIndex + this.myDataTable.get("paginator").rowsThisPage); this.getPage(newStartRecordIndex); }; YAHOO.util.Event.addListener(YAHOO.util.Dom.get("prevLink"), "click", this.getPreviousPage, this, true); YAHOO.util.Event.addListener(YAHOO.util.Dom.get("nextLink"), "click", this.getNextPage, this, true); // Override function for custom sorting this.myDataTable.sortColumn = function(oColumn) { // Which direction var sDir = "asc"; // Already sorted? if(oColumn.key === this.get("sortedBy").key) { sDir = (this.get("sortedBy").dir === "asc") ? "desc" : "asc"; } var oPag = this.get("paginator"); var newBookmark = "sort=" + oColumn.key + "&dir=" + sDir + "&results=" + oPag.rowsThisPage + "&startIndex=0"; YAHOO.util.History.navigate("myDataTable", newBookmark); }; }, this, true); }; });

### YUI Logger Output:

Note: You are viewing this example in debug mode with logging enabled. This can significantly slow performance.

Reload with logging
and debugging disabled.

### DataTable Control (beta) Examples:

- Basic Example
- Progressive Enhancement
- Custom Cell Formatting
- Nested headers
- JSON Data Over XHR
- XML Data Over XHR With POST
- Textual Data Over XHR
- Local XML Data
- Client-side Pagination
- Client-side Sorting
- Server-side Pagination
- Server-side Sorting
- Server-side Pagination and Sorting, with Browser History Manager
- Fixed Scrolling
- Row Selection
- Cell Selection
- Inline Cell Editing
- Context Menu Integration
- Complex Example of Multiple Features
- Datatable with Autocomplete
- Skinning Model

### More DataTable Control (beta) Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2007 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings