Search code examples
javascriptajaxyui

AJAX Request Returns Doubled List of Objects - YUI


I am using YUI's Datatable Column Formatter to format some data returned from an AJAX request. Here's the config:

var dataTable = new Y.DataTable(
{
    id: 'my-table',
    height: '500px',
    width: '500px'
});
var columns = [{
        key: 'id',
        label: 'ID'
    }, {
        label: 'Name',
        formatter: function (o) {
            console.log(o.data);
            return o.data.name; 
        }
    },
    {   
        key: 'department',
        label: 'Department'
    }
];

function search(){
    dataSource = new Y.DataSource.IO({source: '/search' });
    dataSource.sendRequest({
        dataType: 'json',
        on: {
            success: function(e) {
                response = e.data.responseText;             
                data = Y.JSON.parse(response);
                dataTable.set('columns', columns);
                dataTable.set('data', data.content); 
            },
            failure: function(e) {
                //do stuff
            }
        });
    }

My table gets populated fine

enter image description here

And this is returned from the console

Object {id: 1, name: "Bob", department: 001}
Object {id: 2, name: "Andy", department: 003}

However if I launch the request a second time, the number of Objects returned doubles

Object {id: 1, name: "Bob", department: 001}
Object {id: 2, name: "Andy", department: 003}
Object {id: 1, name: "Bob", department: 001}
Object {id: 2, name: "Andy", department: 003}

While the data still displays, this duplication breaks functionality elsewhere. Additionally, no matter the number of times the request is launched, only the doubled list returns. Any idea why the Objects are getting combined?


Solution

  • Try removing the existing data on each AJAX request. $('#myTableID').remove() and then recreate. It seems your AJAX call is appending to the existing content