【问题标题】:Laravel Chart JS change data with dropdownLaravel Chart JS 使用下拉菜单更改数据
【发布时间】:2022-01-06 04:11:21
【问题描述】:

我正在尝试显示从下拉框中获取特定描笼涯(村庄或地区)的图表中的数据。因此,例如,我有一张图表显示过去十年中一个描笼涯的男性和女性人数,我只需要从所述下拉框中选择一个特定的,图表就会更改显示的数据。我正在尝试通过 ajax 和 Chart.js 来做到这一点。

控制器

public function demoHistory()
{
    $gendersbrgy = DB::table('demographics')
        ->selectRaw('sum(case when Q4=\'Male\' then 1 else 0 end) as one,
     sum(case when Q4=\'Female\' then 1 else 0 end) as two,
     year(created_at) as year')
        ->where('currentbrgy', $brgy)
        ->groupBy('brgy', 'year')
        ->orderBy('year', 'desc')
        ->limit(11)
        ->get();

    return response()->json(compact('gendersbrgy');
}

where 子句中的$brgy 变量是我理想的放置变量的位置。我对此很陌生。

JavaScript

const brgy = document.getElementById('brgyselector');
brgy.addEventListener('change', changeBrgy);

function changeBrgy() {
    //DO STUFF HERE
}

Chart of Genders with Barangay Dropdown

有人知道怎么做吗?

【问题讨论】:

  • chart.js 实例中有一个可用的更新功能。您可以使用新记录更新数据。

标签: javascript ajax laravel chart.js


【解决方案1】:

您需要使用update() 来更新 ajax 成功的图表数据。 也许你可以这样做: (也有在 ajax 中使用的示例图表代码)

var ctx_live = document.getElementById("mycanvas");
var myChart = new Chart(ctx_live, {
  type: 'bar',
  data: {
    labels: [],
    datasets: [{
      data: [],
      borderWidth: 1,
      borderColor:'#00c0ef',
      label: 'liveCount',
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: "Chart.js - Dynamically Update Chart Via Ajax Requests",
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true,
        }
      }]
    }
  }
});

// logic to get new data
var getData = function() {
    var e = document.getElementById("brgyselector");
    var strUser = e.value;
      $.ajax({
        url: 'url_to_controller_action',
        success: function(data) {
          // process your data to pull out what you plan to use to update the chart
          // e.g. new label and a new data point
          
          // you can use loop through response data
          // add new label and data point to chart's underlying data structures
          myChart.data.labels.push("Label");
          myChart.data.datasets[0].data.push('set point');
          
          // re-render the chart
          myChart.update();
        }
      });
};

const brgy = document.getElementById('brgyselector');
brgy.addEventListener('change', getData);

我不知道您的 ajax 响应数据是什么样的。因此,您可以在 ajax 成功更新图表数据时根据需要进行修改/设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 2014-05-27
    • 2020-03-29
    • 1970-01-01
    相关资源
    最近更新 更多