Example: DataTable + DataSource.Get + JSON Data

This example shows how to populate a DataTable with data from the Yahoo! Local webservice retrieved via a YQL query. First we create a DataSource.Get instance pointing to YQL, then using the DataTableDataSource plugin we can load data for pizza places near our office.

In this example, we render the DataTable first, then load data into it in a separate call.

Populating Your DataTable with Remote Data Using DataSource.Get

Your table can be easily popluated with remote JSON data from a JSONP webservice by creating a DataSource instance and using the DataTableDataSource plugin to load the data into a DataTable.

Start with the use() statement:

YUI().use("datatable", "datasource-get", "datasource-jsonschema", "datatable-datasource", function(Y) {
});

Next create a DataSource.Get instance pointing to YQL. The YQL Console makes it easy to determine the REST URL we want to send. You also need to define the correct schema for the DataSourceJSONSchema plugin.

var dataSource = new Y.DataSource.Get({
    source: "http://query.yahooapis.com/v1/public/yql?"+
        "q=select%20*%20from%20local.search%20where%20zip%3D%2794089%27%20"+
        "and%20query%3D%27pizza%27&format=json&"+
        "env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
});

dataSource.plug(Y.Plugin.DataSourceJSONSchema, {
    schema: {
        resultListLocator: "query.results.Result",
        resultFields: [ "Title", "Phone", "Rating" ]
    }
});

This is a good time to call sendRequest to make sure the data returns as expected.

dataSource.sendRequest({
    callback: {
        success: function(e) {
            Y.log(e);
        }
    }
});
Results:
{
    "query": {
        ...
        "results": {
            "Result":[
                {
                    "Title" : "Giovannis Pizzeria",
                    "Phone" : "(408) 734-4221",
                    ...
                    "Rating": {
                        "AverageRating": "4",
                        ...
                    }
                },
                {
                    "Title" : "Pizza",
                    "Phone" : "(800) 555-1212",
                    ...
                    "Rating": {
                        "AverageRating":"NaN",
                        ...
                    }
                },
                ...
            ]
        }
    }
}

Uh oh. The Rating data we're receiving is an object rather than a single value. It looks like Rating.AverageRating is what we want, but it's a numeric string, and sometimes the unfortunate value "NaN".

We'll add a locator to the schema to extract the Rating.AverageRating value for our Rating data field, and also a parser that will convert the numeric string into a real number, using -1 for restaurants that haven't received a rating yet. It's a good policy to store the table model data as the appropriate type.

schema: {
    resultListLocator: "query.results.Result",
    resultFields: [
        "Title",
        "Phone",
        {
            key: "Rating",
            locator: "Rating.AverageRating",
            parser: function (val) {
                return isNaN(val) : -1 : +val;
            }
        }
    ]
}

Now that the DataSource is created properly, define the columns that you want your table to show. These columns map directly to the parameter names returned in the data. We'll add a formatter to the Rating column to deal with those -1s, instead displaying "(none)".

var cols = [
    "Title",
    "Phone",
    {
        key: "Rating",
        formatter: function (o) {
            // formatters can either return the new content or update o.value
            if (o.value === -1) {
                o.value = "(none)";
            }
        }
    }
];

Now you are ready to create a DataTable using the columns you have defined. When you plug the instance with the DataTableDataSource plugin, point to your DataSource instance. After you render the table, load the data via the plugin.

var table = new Y.DataTable({
    columns : cols,
    summary : "Pizza places near 98089",
    caption : "Table with JSON data from YQL"
});

table.plug(Y.Plugin.DataTableDataSource, { datasource: dataSource });

table.render("#pizza");

table.datasource.load();

One final change you can make is to split the URL between the DataSource source value and the request value sent to the DataTableDataSource plugin. Splitting the URL this way facilitates making future requests to the same DataSource. You can see this in the Full Code Listing below.

Full Code Listing

Note: be sure to add the yui3-skin-sam classname to the page's <body> element or to a parent element of the widget in order to apply the default CSS skin. See Understanding Skinning.

<body class="yui3-skin-sam"> <!-- You need this skin class -->
<div id="pizza"></div>

<script>
YUI().use("datatable", "datasource-get", "datasource-jsonschema", "datatable-datasource", function (Y) {

    var url = "http://query.yahooapis.com/v1/public/yql?format=json" +
                  "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
        query = "&q=" + encodeURIComponent(
                'select * from local.search ' +
                'where zip = "94089" and query = "pizza"'),
        dataSource,
        table;

    dataSource = new Y.DataSource.Get({ source: url });

    dataSource.plug(Y.Plugin.DataSourceJSONSchema, {
        schema: {
            resultListLocator: "query.results.Result",
            resultFields: [
                "Title",
                "Phone",
                {
                    key: "Rating",
                    locator: "Rating.AverageRating",
                    parser: function (val) {
                        // YQL is returning "NaN" for unrated restaurants
                        return isNaN(val) ? -1 : +val;
                    }
                }
            ]
        }
    });

    table = new Y.DataTable({
        columns: [
            "Title",
            "Phone",
            {
                key: "Rating",
                formatter: function (o) {
                    if (o.value === -1) {
                        o.value = '(none)';
                    }
                }
            }
        ],
        summary: "Pizza places near 98089",
        caption: "Table with JSON data from YQL"
    });
    
    table.plug(Y.Plugin.DataTableDataSource, { datasource: dataSource });

    table.render("#pizza");

    table.datasource.load({ request: query });
});
</script>

Lighten the module payload

The datatable module includes a number of features not used in this example. For a smaller module payload, use the datatable-base module.

// datatable-base includes only basic table rendering, but in this case,
// that's enough.
YUI().use("datatable-base", "datasource-get", "datasource-jsonschema", "datatable-datasource", function(Y) {

    ...

    var table = new Y.DataTable({
        columns : cols,
        summary : "Pizza places near 98089",
        caption : "Table with JSON data from YQL"
    });

    table.plug(Y.Plugin.DataTableDataSource, { datasource: dataSource });

    table.render("#pizza");

    table.datasource.load();

});