$('#example').DataTable().column(4).data().sum(); returning 0
$('#example').DataTable().column(4).data().sum(); returning 0
Sample case: https://datatables-ecommerence.000webhostapp.com/
I have no errors on the console or w3validator.
` <script src="https://cdn.datatables.net/plug-ins/1.10.19/api/sum().js"></script>`
$(document).ready(function() {
var sum = $('#example2').DataTable().column(4).data().sum();
$('#total').html(sum);
});
I tried other columns too and they all return 0.
=====
Since I have two tables, I may have to make my own personal script because https://cdn.datatables.net/plug-ins/1.10.19/api/sum().js uses example (not example2). That is the only thing I can think of that could be wrong.
I will post any other updates as I will be working on this for a while.
This question has an accepted answers - jump to answer
Answers
My guess is
var sum = $('#example2').DataTable().column(4).data().sum();
is running before the ajax response. Try placing it in eitherinitComplete
ordrawCallback
so it runs after the ajax resposne and the table is loaded.Kevin
Exactly what Kevin says (as usual ). You are running the function before the data has been loaded, so it is correct in reporting
0
as the sum.Allan
This still returns 0 (the only way I got it to return no errors). I am assuming this code is the closest as its the only one I had with no errors or the table disappearing (I tried many ways).
Is it best to put the drawback within the main header? or separate.
Here is an example:
http://live.datatables.net/segeriwe/1/edit
I took your code in lines 27 and 28 and placed them in
drawCallback
. I changed the column to 5 which has numeric values. The example is using SSP.Kevin
Ok here is full code solution that answered my question...
Interestingly enough, (I just noticed today) this produces the sum of the current page only (I will try to find a work around). Or I might just take off pages for the second table entirely anyway.
That is because you are using server side processing. The
sum()
method can only sum the data in the client which is the current page.One option would be to have your server code run a query to sum that column then return that in the JSON response. You can then use the
xhr
event to get the sum out of thejson
object passed into the event and use$('#total').html(sum);
in the event to display it.Something like this assuming the sever script appends the
sum
object to the returned json:Kevin
Ok. Maybe getting the sum using SQL would be easier.
But with your method I will give it some research and post back any end results.