[Chartjs]-Trying to load a chart with chart.js, through ajax and php

3👍

That’s not how jQuery html is intended to be used. You are not supposed to load entire HTML pages including scripts using html method; it’s a big security issue and that’s why most likely is not going to work that way.

Instead, you should load all the libraries needed to the main page and fetch using AJAX, ONLY the data needed for the chart. Then use that data to generate/draw/append the chart inside your page.

For example using your code:

$.ajax({
    type    : 'POST',
    url     : `//${base_url}/ajax2/dashboard-pie-json-data.php`,
    success : function(data) {
        var enquiriesquantitysalespeople = data;
        // Return just the data needed for the chart using JSON.
        // For example, enquiriesquantitysalespeople should contain data such as:
        // {
        //    type: 'doughnut',
        //    data: {
        //        datasets: [{...}],
        //        labels: ['Lee Davies','Lee Davies']
        //    },
        //    options: {
        //        responsive: true,
        //        ...
        //    }
        //    ...
        // }

        // Then get the 2D context of element you want to render the chart
        var enquiriesquantitysalespeople_chart = document
            .getElementById('dashboard_graph_quantity_enquiries_salespeople')
            .getContext('2d');

        // And create the chart using the data you just fetched to the 2D context
        window.myDoughnut = new Chart(
            enquiriesquantitysalespeople_chart,
            enquiriesquantitysalespeople
        );
    }
});

Sample Data return using PHP

<?php

header('Content-type: application/json');

$data = [
  'type' => 'doughnut',
  'data' => [
    'datasets'=> [[
      'data'=> [6, 1],
      'backgroundColor' => ["#2585fe", "#71b0ff", "#29bb52", "#497956", "#fcb858", "#f8cd90"],
      'borderWidth'=> 0,
    ]],
    'labels'=> ['Lee Davies','Lee Davies']
  ],
  'options'=> [
    'responsive'=> true,
    'legend'=> [
      'position'=> 'right',
      'textDirection'=> 'rtl',
      'labels'=> [
        'boxWidth'=> 14,
        'fontSize'=> 14,
        'fontColor'=> "#000",
        'fontFamily'=> 'proxima-nova',
      ]
    ],
    'animation'=> [
      'animateScale'=> true,
      'animateRotate'=> true
    ]
  ]
];

echo json_encode($data);

This code snippet will make the AJAX request and dynamically create the canvas element each time the AJAX call finishes after we hit the load button.

Run it to see it in action:

document.getElementById('load').addEventListener('click', function() {
  $.ajax({
    type: 'POST',
    dataType : 'json',
    url: 'https://zikro.gr/dbg/so/65660138/data.php',
    success : function(data) {
      // console.log('Got AJAX data', data);
      $('#dashboard_pie_pop_cont')
        .empty()
        .append(
          $('<canvas/>', {
            id: 'dashboard_graph_quantity_enquiries_salespeople'
          })
        );

      var enquiriesquantitysalespeople_chart = 
        document
          .getElementById('dashboard_graph_quantity_enquiries_salespeople')
          .getContext('2d');

      window.myDoughnut = new Chart(
        enquiriesquantitysalespeople_chart,
        data
      );
    }
  });
});
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<script src="https://www.chartjs.org/dist/2.9.3/Chart.min.js"></script>

<button id="load">Load AJAX Chart</button>
<div id="dashboard_pie_pop_cont" style="width: 100%; height: 100px"></div>

iFrame solution

Also, an other option is to load the chart page inside an iFrame and not make an AJAX call at all.

Leave a comment