dynamic column value calculation

dynamic column value calculation

mehtimehti Posts: 35Questions: 13Answers: 0

I am pulling data from sql using ajax call. imagine im getting 2 columns back time and distance from DB, i would like to use these values to calculate speed by dividing distance by time. so at the end i'll have three columns two would be from DB and third would be their combination. is it possible to do so?

here is simple call to DB

table = $('#results').DataTable({
"ajax": {
async: false,
global: false,
url: "../php/getResults.php",
dataType: "json"
},
"columns": [{
"data": "Time"
}, {
"data": "Distance"
}, {
"data": "Speed" //needs to be calculate using above two data inputs.
}],
"order": [
[2, 'asc']
]
});

This question has an accepted answers - jump to answer

Answers

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 394

    Why not do it in your PHP query, so the database returns the calculation?

  • mehtimehti Posts: 35Questions: 13Answers: 0

    Thanks for your reply tangerine. I've simplified the problem as a way to make it a bit easier to understand, unfortunately I can't (or rather don't want to) do it in the PHP query.

  • mehtimehti Posts: 35Questions: 13Answers: 0

    I think I need to use this functionality, however I haven't figured out how yet. I keep getting [object Object]

    https://datatables.net/reference/option/rowCallback

    when I add the following:

    "rowCallback": function (row, data) {
    $('td:eq(2)', row).html(data[1] / data[0]);
    }

  • mehtimehti Posts: 35Questions: 13Answers: 0

    okay this is how you resolve the problem I had...

    createdRow: function (row, data) {
    $('td:eq(2)', row).html( data['Distance']/data['Time'] );
    }

  • allanallan Posts: 62,448Questions: 1Answers: 10,251 Site admin
    Answer ✓

    Use columns.render to perform the calculation.

    Allan

  • mehtimehti Posts: 35Questions: 13Answers: 0

    Thanks Alan!

This discussion has been closed.