user6063812 user6063812 - 9 months ago 64
Ajax Question

Add calculated (Percent) column to a Datatable driven by xml ajax source?

I would like to be able to add a percent column calculated based on 2 columns where the data is supplied by ajaz xml:

$(document).ready(function () {
var itemTable = $('#items').DataTable({
ajax: {
url: "/api/itemList",
dataSrc: ""
columns: [
{ data: 'item' },
{ data: 'buyPrice' },
{ data: 'sellPrice' },

I would like to be able to add a calculated column something like this:

{ data: 'percent' (buyPrice/sellPrice*100 % }

Here is an example of my source XML:


The XML is generated in the MVC application so it's preferable to have the calculation done client side. Thank you.

EDIT: I would like to be able to retain full column header sorting if possible - or else I will be forced to do the percent calculation on the database side. Unless I can do it on the XML but I have no clue about that.


Sorting fixed see below comment HOWEVER - although it does what I want it's not sorting!

Computing values

Finally, to create a margin column from the price and cost fields we can use a function to compute the required values - note that in this case is null - as a result the first parameter passed into the columns.render method is also null, but the third parameter provides access to the original data source object, so we can continue use the data from there:

data: null,
render: function ( data, type, row ) {
    return Math.round( ( row.price - row.cost ) / row.price * 100 )+'%';