I am refreshing my Bar Chart on change of a drop down. I just Want to know that am I doing it in correct way. In my code every time I am replacing my existing canvas with new one. Is there any better way to achieve same thing?
My JS Code:
var chart_= function () {
$('#canvas_id').replaceWith('<canvas id="canvas_id" style="height:280px"></canvas>');
$.ajax({
type: 'POST', //post method
url: 'url', //ajaxformexample url
dataType: "json",
success: function (result, textStatus, jqXHR)
{
// GENERATE CHART DATA
var labels = result.obj.map(function (e) {
return e.label;
});
var data = result.obj.map(function (e) {
return e.data;
});
new Chart($("#canvas_id"), {
type: 'bar',
options: options_object,
data: {
labels: labels,
datasets: [
{
label: "",
backgroundColor: '#00c0ef',
data: data
}
]
}
});
}
});
};
I am refreshing my Bar Chart on change of a drop down. I just Want to know that am I doing it in correct way. In my code every time I am replacing my existing canvas with new one. Is there any better way to achieve same thing?
My JS Code:
var chart_= function () {
$('#canvas_id').replaceWith('<canvas id="canvas_id" style="height:280px"></canvas>');
$.ajax({
type: 'POST', //post method
url: 'url', //ajaxformexample url
dataType: "json",
success: function (result, textStatus, jqXHR)
{
// GENERATE CHART DATA
var labels = result.obj.map(function (e) {
return e.label;
});
var data = result.obj.map(function (e) {
return e.data;
});
new Chart($("#canvas_id"), {
type: 'bar',
options: options_object,
data: {
labels: labels,
datasets: [
{
label: "",
backgroundColor: '#00c0ef',
data: data
}
]
}
});
}
});
};
Share
Improve this question
edited Jul 30, 2017 at 7:35
ansh
asked Jul 29, 2017 at 7:04
anshansh
6233 gold badges12 silver badges27 bronze badges
1 Answer
Reset to default 25Definitely some better ways, I have been using Chart.js for some live updating charts and a good way to accomplish what you want is to declare an chart with some of the settings predefined initially.
var chart = new Chart( canvas, {
type: "bar",
data: {}
options: {}
}
This way, whenever you need to update the chart, you just access the already existing chart. And update the data to what you get from your ajax call, and use the chart.update() method, so you can keep using the pre-existing canvas
$.ajax({
type: 'POST', //post method
url: 'url', //ajaxformexample url
dataType: "json",
success: function (result, textStatus, jqXHR)
{
chart.data = result;
chart.update();
}
});
Hope this helps!