Search code examples
canvasjs

CanvasJS changing chart-type based on drop-down value


I want to change the chart-type based on the drop-down value. I had tried and followed the example but it still unable to work. I'm not sure which part that i had missed. I am using JavaScript Charts & Graphs from JSON Data Using AJAX. The code below:

<script src="../js/custom.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/>

<script>
window.onload = function () {

var dataPoints = [];

$.getJSON( "<?php echo $url; ?>", function( json ) {

  for (var i = 0; i < json.dates.length; i++) {
        dataPoints.push({
            x: new Date(json.dates[i]),
            y: json.values[i]
        });
    }

    var chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    exportEnabled: true,
    theme: "dark2",
    title: {
        text: "REPORT"
    },
    axisY: {
        title: "Qty"
    },
    data: [{
        type: "column", 
        //indexLabel: "{y}", //Shows y value on all Data Points
        yValueFormatString: "#,### Units",
        indexLabelFontColor: "#5A5757",
        indexLabelPlacement: "outside",
        dataPoints: dataPoints
    }]
});

chart.render();
 })
    .done(function(){
        alert("Completed");
    })
    .fail(function(e){
        console.log('error:');
        console.error(e);
    })
    .always(function(){
        alert("always runs");
    });
}
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change",  function(){
        for(var i = 0; i < chart.options.data.length; i++){
            chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
    }
    chart.render();
});
</script>


Drop-down list:

<select id="chartType" class="form-control" name="chartType">
                                            <option value="column">Column</option>
                                            <option value="line">Line</option>
                                            <option value="bar">Bar</option>
                                            <option value="pie">Pie</option>
                                            <option value="doughnut">Doughnut</option>
                                        </select>

Thank you in advance.


Solution

  • It just seems like variable scope issue, you are creating chart inside AJAX but trying to access it outside during changing the chart type, it would have thrown error in Browser Console. I would suggest you to do it outside AJAX and update just dataPoints inside AJAX.

    Here is the updated / working code (Sample JSON with just 1 dataPoint is stored in: https://api.myjson.com/bins/18hgaa):

    var dataPoints = [];
    var chart;
    $.getJSON("https://api.myjson.com/bins/18hgaa", function(json){
      for (var i = 0; i < json.dates.length; i++) {
        dataPoints.push({
          x: new Date(json.dates[i]),
          y: json.values[i]
        });
      }
    }).done(function(){
    		chart = new CanvasJS.Chart("chartContainer", {
        animationEnabled: true,
        exportEnabled: true,
        theme: "dark2",
        title: {
          text: "REPORT"
        },
        axisY: {
          title: "Qty"
        },
        data: [{
          type: "column", 
          //indexLabel: "{y}", //Shows y value on all Data Points
          yValueFormatString: "#,### Units",
          indexLabelFontColor: "#5A5757",
          indexLabelPlacement: "outside",
          dataPoints: dataPoints
        }]
      });
    	chart.render();
    });
    var chartType = document.getElementById('chartType');
    chartType.addEventListener( "change",  function(){
      for(var i = 0; i < chart.options.data.length; i++){
        chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
      }
      chart.render();
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
    
    <div id="chartContainer" style="height: 360px; width: 100%;"></div>
    <select id="chartType" class="form-control" name="chartType">
      <option value="column">Column</option>
      <option value="line">Line</option>
      <option value="bar">Bar</option>
      <option value="pie">Pie</option>
      <option value="doughnut">Doughnut</option>
    </select>