Javascript – How to make YUI datasource parse Null values in the dataset

ajaxdatasourcejavascriptyuiyui-datatable

I am using YUI datatable and datasource to render data in one of my projects. The data returned happens to be NULL and YUI datasource is unable to parse it.

Below is the declaration code of datasource and datatable. For readability sake, I am seperating each of the declarations.

Column Descriptions declaration

var columnDescription = 
    [
        {key:'Requirements'},
        {key:'abc'},
        {key:'xyz'}
    ];

This columnDescription is set in the function below.

DataSource Declaration

var dataSrcSample = new YAHOO.util.FunctionDataSource(getDataGrid);
myDataSource.connMethodPost = true;
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.responseSchema = {
    fields:['Requirements', 
        {key:'abc',parser:YAHOO.util.DataSource.parseString},
        {key:'xyz',parser:YAHOO.util.DataSource.parseString}]
};

getDataGrid function makes the call to server side to get the data from the server.
Below is the table definition itself.

YAHOO.example.sampleTable = function()
{
    var columnDesc=columnDescription;
    var myDataSource = dataSrcSample;
    var oConfigs = 
    {
        width:'100%'
    };

    var myDataTable = new YAHOO.widget.DataTable("tableContainerDiv", columnDesc, myDataSource, oConfigs);
}();

tableContainerDiv is declared in the html page. This is the container div.
The function that gets the JSON data from server.

function getDataGrid()
{
      //calls backend and gets the data
}

The function is returning json string that has some null values. Datasource constructor is complaining following problems.

  • ERROR_DATAINVALID
  • ERROR_DATANULL

I checked the yui documentation and found that the string parser does not parse null values. I am wondering if there is any way to parse this data. Do I have to handleResponse parse the raw data? Any suggestions appreciated.

Best Answer

You need to create your own parser perhaps?

function parseNull(value) {
    // This exact logic may be incorrect, depends on what you get for value in the null case
    if (value=='null') {
        return null;
    }
    YAHOO.util.DataSource.parseString(value);
}

Then you can specify:

{key:'abc',parser:parseNull}

To use your new parser