Search code examples
phpjquerychart.jsjqvmap

dynamic data in ChartJS


I'm using ChartJS and JQVMaps in a website to create an interactive world map that displays info graphics when a user clicks on a region. The ChartJS plugin allows you to assign the chart's data values as an array like so:

var pieData = [
        {
            value: 20,
            color:"#878BB6"
        },
        {
            value : 40,
            color : "#4ACAB4"
        },
        {
            value : 10,
            color : "#FF8153"
        },
        {
            value : 30,
            color : "#FFEA88"
        }
    ];

For my project, I will need to generate these data values dynamically based on what region the user clicked. The final site will be through WordPress. Is it possible to feed the chart's build script

new Chart(pie).Pie(pieData);

a PHP or jQuery function that could call one of several different arrays in pieData? What might that coding look like? I'm somewhat new to PHP and jQuery so any help is greatly appreciated.

The demo is up on GitHub if you want to take a look. Thanks!


Solution

  • You can use an AJAX request to get the data from the server. Below is an example using PHP to build out data. Although you would need to make it conditional based on region.

    onRegionClick: function(element, code, region) {
     $.ajax('/get_chart_data.php', {
      data: {region: region},
      dataType: 'json',
      success: function(response) {
        new Chart(pie).Doughnut(response.pieData, pieOptions);
      }
    });
    

    get_chart_data.php

    <?php
    
    // Check which region was passed
    //$_REQUEST['region']
    // Based on region build chart data
    
    $chartData = new stdClass();
    
    $pieData = array();
    $pie1= new stdClass();
    $pie1->value = 20;
    $pie1->color = '#878BB6';
    $pieData[] = $pie1;
    
    $pie2= new stdClass();
    $pie2->value = 40;
    $pie2->color = '#4ACAB4';
    $pieData[] = $pie2;
    
    $chartData->pieData = $pieData;
    echo json_encode($chartData);
    ?>
    

    One method of switching based on region

    <?php
    
    $region1Pie = array(20, '#878BB6', 40, '#4ACAB4', 10, '#FF8153', 30, '#FFEA88');
    $region2Pie = array(15, '#878BB6', 20, '#4ACAB4', 25, '#FF8153', 30, '#FFEA88');
    $region3Pie = array(9, '#878BB6', 60, '#4ACAB4', 25, '#FF8153', 12, '#FFEA88');
    
    $chartData = new stdClass();
    $pieData = array();
    
    // Swtich based on region
    switch($_REQUEST['region']) {
      case 1:
        $pieArray = $region1Pie;
        break;
      case 2:
        $pieArray = $region2Pie;
        break;
      case 3:
        $pieArray = $region3Pie;
        break;
    }
    
    for($i=0; $i<count($pieArray); $i+=2) {
      $pie= new stdClass();
      $pie->value = $pieArray[$i];
      $pie->color = $pieArray[$i+1];
      $pieData[] = $pie;
    }
    
    $chartData->pieData = $pieData;
    echo json_encode($chartData);
    
    ?>