Display an Apex Chart in DataTable

2.4k views Asked by At

I'm struggling to add a chart in a datatable. I'm using Apex chart and DataTable jquery plugins.

I'm getting the following message "Error: Element not found apexcharts.min.js:14". I suppose is due to id="apex-mixed-2 is not yet available when Apex renders the chart but I cannot find a solution.

By the moment I would like to add the same chart for all the data rows.

Datatable Code

    $(document).ready(function() {
    "use strict";
    $("#products-datatable").DataTable({
        ajax:{url: "../assets/data/jsdata.json",dataSrc:""},
        columns: [
            {
                "data": "Url",
                "render": function(data, type, row) {
                    return '<img src="'+data+'" alt="table-user" class="mr-2 rounded-circle" style="height: 70px;"/>';
                }
            },       
            { "data": "Customer" },
            { "data": "Phone" },
            { "data": "Balance" },
            { "data": "Orders" },
            { "data": "Last Order" },
            { "data": "Status" }
            {
                "data": "Graph",
                "render": function(data, type, row, meta) {
                    return ' <div id="apex-mixed-2"</div>';
                }
            }            
        ]
    })
});

A simple Apex chart

   var options = {
      series: [{
        name: "Desktops",
        data: [10, 41, 35, 51, 49, 62, 69, 91, 148]
    }],
      chart: {
      height: 350,
      type: 'line',
      zoom: {
        enabled: false
      }
    },
    dataLabels: {
      enabled: false
    },
    stroke: {
      curve: 'straight'
    },
    title: {
      text: 'Product Trends by Month',
      align: 'left'
    },
    grid: {
      row: {
        colors: ['#f3f3f3', 'transparent'], // takes an array which will be repeated on columns
        opacity: 0.5
      },
    },
    xaxis: {
      categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep'],
    }
    };

    var chart = new ApexCharts(document.querySelector("#apex-mixed-2"), options);
    chart.render();
1

There are 1 answers

2
Rory McCrossan On

To execute code after the AJAX request made by Datatables to load the content has completed use the drawCallback property.

$('#products-datatable').DataTable({
  ajax: {
    url: '../assets/data/jsdata.json',
    dataSrc: ''
  },
  drawCallback: () => {
    // call your chart initialisation code here...
  }, 
  columns: [
    {
      data: 'Url',
      render: data => `<img src='${data}' alt='table-user' class='mr-2 rounded-circle' style='height: 70px;'/>`
    },       
    { data: 'Customer' },
    { data: 'Phone' },
    { data: 'Balance' },
    { data: 'Orders' },
    { data: 'Last Order' },
    { data: 'Status' }
    {
      data: 'Graph',
      render: () => ' <div id="apex-mixed-2"></div>'
    }            
  ]
})