YUI Library Home

YUI Library Examples: DataTable Control: Server-side Pagination and Sorting for Dynamic Data

DataTable Control: Server-side Pagination and Sorting for Dynamic Data

This example enables server-side sorting and pagination for data that is dynamic in nature. The generateRequest config and doBeforeLoadData() method allow tight integration with changing values on the server.

Total records (between 0 and 1000):

Code for this example

This example requests fresh data from the DataSource for every change to the DataTable's sorting or pagination states.

The server-side script delivering the DataTable's records will send the data in the following JSON format:

1{"recordsReturned":25, 
2    "totalRecords":1397, 
3    "startIndex":0, 
4    "sort":null, 
5    "dir":"asc", 
6    "pageSize":10, 
7    "records":[ 
8        {"id":"0", 
9        "name":"xmlqoyzgmykrphvyiz", 
10        "date":"13-Sep-2002", 
11        "price":"8370", 
12        "number":"8056", 
13        "address":"qdfbc", 
14        "company":"taufrid", 
15        "desc":"pppzhfhcdqcvbirw", 
16        "age":"5512", 
17        "title":"zticbcd", 
18        "phone":"hvdkltabshgakjqmfrvxo", 
19        "email":"eodnqepua", 
20        "zip":"eodnqepua", 
21        "country":"pdibxicpqipbsgnxyjumsza"}, 
22        ... 
23    ] 
24
view plain | print | ?

CSS

1/* No custom CSS. */ 
view plain | print | ?

The markup

1<p>Total records (between 0 and 1000): <input type="text" id="total" value="1000"<input type="button" id="update" value="Update"></p> 
2<div id="dynamicdata"></div> 
view plain | print | ?

Javascript

1YAHOO.example.DynamicData = function() { 
2    // Column definitions 
3    var myColumnDefs = [ // sortable:true enables sorting 
4        {key:"id", label:"ID", sortable:true}, 
5        {key:"name", label:"Name", sortable:true}, 
6        {key:"date", label:"Date", sortable:true, formatter:"date"}, 
7        {key:"price", label:"Price", sortable:true}, 
8        {key:"number", label:"Number", sortable:true
9    ]; 
10 
11    // Custom parser 
12    var timestampToDate = function(oData) { 
13        // timestamp comes from server in seconds 
14        // JS needs it in milliseconds 
15        return new Date(oData*1000); 
16    }; 
17 
18    // DataSource instance 
19    var myDataSource = new YAHOO.util.DataSource("assets/php/json_proxy.php?"); 
20    myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON; 
21    myDataSource.responseSchema = { 
22        resultsList: "records"
23        fields: [ 
24            {key:"id", parser:"number"}, 
25            {key:"name"}, 
26            {key:"date", parser:timestampToDate}, 
27            {key:"price",parser:"number"}, 
28            {key:"number",parser:"number"
29        ], 
30        // Access to values in the server response 
31        metaFields: { 
32            totalRecords: "totalRecords"
33            startIndex: "startIndex" 
34        } 
35    }; 
36     
37    // Customize request sent to server to be able to set total # of records 
38    var generateRequest = function(oState, oSelf) { 
39        // Get states or use defaults 
40        oState = oState || { pagination: null, sortedBy: null }; 
41        var sort = (oState.sortedBy) ? oState.sortedBy.key : "id"
42        var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc"
43        var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0; 
44        var results = (oState.pagination) ? oState.pagination.rowsPerPage : 25; 
45 
46        var total = YAHOO.util.Dom.get("total").value *1; 
47        // Validate input 
48        if(!YAHOO.lang.isNumber(total) || total < 0 || total > 1000) { 
49            YAHOO.util.Dom.get("total").value = 0; 
50            total = 0; 
51            alert("Total must be between 0 and 1000."); 
52        } 
53 
54        // Build custom request 
55        return  "sort=" + sort + 
56                "&dir=" + dir + 
57                "&startIndex=" + startIndex + 
58                "&results=" + (startIndex + results) + 
59                "&total=" + total; 
60    }; 
61 
62    // DataTable configuration 
63    var myConfigs = { 
64        generateRequest: generateRequest, 
65        initialRequest: generateRequest(), // Initial request for first page of data 
66        dynamicData: true// Enables dynamic server-driven data 
67        sortedBy : {key:"id", dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow 
68        paginator: new YAHOO.widget.Paginator({ rowsPerPage:25 }) // Enables pagination  
69    }; 
70     
71    // DataTable instance 
72    var myDataTable = new YAHOO.widget.DataTable("dynamicdata", myColumnDefs, myDataSource, myConfigs); 
73    // Update totalRecords on the fly with values from server 
74    myDataTable.doBeforeLoadData = function(oRequest, oResponse, oPayload) { 
75        oPayload.totalRecords = oResponse.meta.totalRecords; 
76        oPayload.pagination.recordOffset = oResponse.meta.startIndex; 
77        return oPayload; 
78    }; 
79 
80    return { 
81        ds: myDataSource, 
82        dt: myDataTable 
83    }; 
84         
85}(); 
view plain | print | ?

Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

YUI Logger Output:

Logger Console

INFO 329ms (+109) 8:39:03 PM:

LogReader instance0

LogReader initialized

INFO 220ms (+1) 8:39:03 PM:

DataSource instance0

Making connection to live data for "sort=id&dir=asc&startIndex=0&results=25&total=1000"

INFO 219ms (+0) 8:39:03 PM:

DataTable instance yui-dt0

DataTable showing message: Loading...

WARN 219ms (+0) 8:39:03 PM:

DataTable instance yui-dt0

Could not find DragDrop for resizeable Columns

INFO 219ms (+4) 8:39:03 PM:

DataTable instance yui-dt0

TH cells for 5 keys created

INFO 215ms (+0) 8:39:03 PM:

RecordSet instance yui-rs7

RecordSet initialized

INFO 215ms (+2) 8:39:03 PM:

ColumnSet instance yui-cs1

ColumnSet initialized

INFO 213ms (+213) 8:39:03 PM:

DataSource instance0

DataSource initialized

INFO 0ms (+0) 8:39:03 PM:

global

Logger initialized

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

Reload with logging
and debugging disabled.

More DataTable Control Resources:

Copyright © 2011 Yahoo! Inc. All rights reserved.

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