I've put together some code which allows me to query a MySQL database, return the result and populate a chart.js. The problem being that each time the AJAX code runs the chart is rendered over the previous one. I've read through a few similar stackoverflow queries which are recommending the use of myChart.destroy(); or other solutions but I' struggling to work out where this should be inserted into the following code.
Note that I've simplified the code below for simplicity sake.
Any assistance on how to stop this chart 'ghosting' occuring would be greatly appreciated.
<script type="text/javascript">
jQuery(document).ready( function($) {
var valueCheck;
jQuery('#afl_player_year').on( 'change', function () {
afl_player_year = $('#afl_player_year').val();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
dataType: "json",
data: {
action: 'call_player_chart_data',
afl_player_year: afl_player_year,
},
success:function(output){
var y_data1 = output[0];
var y_data2 = output[1];
var x_time = ............
new Chart(document.getElementById("myChart"), {
type: 'bar',
data: {
labels: x_time,
datasets: [{.........
}, {.........
}]
},
options: {
scales: {.........
yAxes: [{.........},{.........},
}]
}
}
});
}
});
}).change();
});
</script>
Related
I have a controller action in my MVC project that creates a json record with the components needed. This is working. The issue I am having is bringing it into a chart.js canvas. This will be a pie chart that shows all the related countries with a count of each. Json has this info. Originally this was setup to use google visualization but I want to use chart.js. I just started using it. Creating charts with static data is no issue but I am pulling the info from a SQL table and creating a json to read from.
I have tried using the same structure and calling the data: data[] but it doesn't work I have also tried data: getData, which is a var for the ajax function. I am getting the data per the council on refresh.
Here is my controller Action
public ActionResult CustomersByCountry()
{
CustomerEntities _context = new CustomerEntities();
var customerByCountry = (from c in _context.Addresses
group c by c.Country into g
orderby g.Count() descending
select new
{
Country = g.Key,
CountCustomer = g.Count()
}).ToList();
return Json(new { result = customerByCountry }, JsonRequestBehavior.AllowGet);
}
And here is the JavaScript/ajax - which is nested in a document.ready function with the rest of the charts.
EDIT - changed Ajax - Still not working
OrdersByCountry()
function OrdersByCountry() {
$.ajax({
url: '/admin/CustomersByCountry',
method: "GET",
dataType: "json",
error: function (_, err) {
console.log(_, err)
},
success: function (data) {
console.log (data);
var customer = $("#customerByCountryPieChart").get(0).getContext("2d");
console.log(customer)
var cpieChart = new Chart(customer, {
type: 'pie',
data: data,
options: {
responsive: true,
title: {
display: true,
text: "Customers By Country",
}
}
});
}
});
};
Edit - The now working code is below.
I changed it to get states instead of country, just to clear up possible confusion. It made more sense to me to get States rather than Country at this point. This is working - meaning displaying the graph, I still need to work on the labels etc.
OrdersByStates()
function OrdersByStates() {
$.ajax({
url: '#Url.Action("CustomersByStates", "Admin")',
data: JSON,
contentType: "application/json; charset=utf-8",
method: "get",
dataType: "json",
error: function (_, err) {
console.log(_, err)
},
success: function (response) {
console.log(response);
var jsonresult = response
var labels = jsonresult.result.map(function (e) {
return e.State;
});
var data = jsonresult.result.map(function (e) {
return e.CountCustomer;
});;
var ctx = document.getElementById("CustomerByStatePieChart").getContext("2d");
var cpieChart = new Chart(ctx, {
type: 'pie',
data:
{
datasets: [
{
backgroundColor: ["#46BFBD", "#F7464A"],
hoverBackgroundColor: ["#5AD3D1", "#FF5A5E"],
label: "Orders",
data: data,
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Customers By Country",
}
}
});
}
});
};
});
try:
var cpieChart = new Chart(customer, {
type: 'pie',
data: data.result,
options: {
responsive: true,
title: {
display: true,
text: "Customers By Country",
}
}
});
the response from the server "data" var on your request is {result: LIST}
I have several different charts that I am rendering with c3js via ajax, and I currently have a lot of repeated ajax code that I would like to cut down on.
Each ajax call on success generates a c3js chart, but with different display types/options. Is there a way I can have a generic c3js generate and just pass in the options?
$.ajax({
url: url,
data: {'chart': chart, 'start': start, 'end': end},
type: 'post',
dataType: 'json',
beforeSend: function () {
//code
},
success: function (data) {
if (data.success) {
//code
c3.generate({
bindto: '#chart-data',
data: {
columns: data.active,
type: 'area',
groups: [data.groups]
},
axis: {
x: {
type: 'category',
categories: data.span
},
y: {
label: 'Label'
}
}
});
} else {
//code
}
}
});
Repeated several times with various chart data types, groups, columns, axis, etc.
What I want:
var chart_options = {bindto: '#chart-data', data:{columns.data.active} //...
function generateChart(param1, param2, param3, chart_options) {
//do some stuff
//ajax call from above
// ....
// on success:
// c3.generate(chart_options)
}
However when I do it this way, because the data.success is inside the function, and I am passing columns: data.active from outside the function, I receive javascript errors for data[i] column not defined.
Thanks
var chart_options = {bindto: '#chart-data', {data: {type: "area"}} //...}
function generateChart(param1, param2, param3) {
//do some stuff
//ajax call from above
// ....
// on success:
// chart_options.data.colums = data.active;
// chart_options.data.groups = [data.groups];
// same for axes…
// c3.generate(chart_options)
}
I'm using Morris Donut for a dashboard I'm working on and retrieving data via AJAX using two date ranges as parameters. The problem I'm facing is when I enter two new date ranges the Donut Chart renders a new one on top of Donut already created upon page load. I've searched about and can see information on using setData(), but I have no idea how to include this within my code.
My Code:
$(document).ready(function () {
var start = $('#SearchStart').val();
var end = $('#SearchEnd').val();
populateDonut(start, end);
});
The search button does the following when clicked:
$('#DateRange').click(function() {
var start = $('#SearchStart').val();
var end = $('#SearchEnd').val();
populateDonut(start, end);
});
Here is the function that is called.
function populateDonut(start, end) {
var param = { start: start, end: end };
$.ajax({
type: "POST",
url: "/WebService.asmx/getDonutData",
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: true,
data: JSON.stringify(param),
success: function (result) {
var data = eval("(" + result.d + ")");
var pieChart = '';
if (data.status == 0) {
var donut = Morris.Donut({
element: 'pieChart',
data: [
{ label: "Inbound", value: data.inbound },
{ label: "Outbound", value: data.outbound },
{ label: "Unanswered", value: data.unanswered }
],
colors: ['#1ca8dd', '#33b86c', '#ebc142'],
resize: true,
formatter: function (x) { return x + "%" }
});
}
}
});
}
Screenshot of what is happening after entering new date ranges:
Try calling $("#pieChart").empty(); before rendering the second chart.
Preferably in here:
$('#DateRange').click(function() {
var start = $('#SearchStart').val();
var end = $('#SearchEnd').val();
// Clear the existing chart before populating new donut
$("#pieChart").empty();
populateDonut(start, end);
});
I tried the below code and it's working with me :
$("#chart-id").empty();
You can use it on each time you call chart data .
I have a script tag like below in my partial view :
<script>
$(function () {
$.ajax({
type: "GET",
url: "/api/ChartsAPI/2",
dataType: "json",
success: function (seriesData) {
console.log(seriesData);
$("#chart").kendoChart({
dataSource: {
data: seriesData
},
series: [{
field: "yaxisData",
name: "Average"
}],
title:
{ #ViewBag.PlaceHolder }
});
}
});
})
</script>
In my controller the view bag data is populated like below :
ViewBag.PlaceHolder = "text:'test'";
But with this configuration, the chart is not getting rendered correctly as the chart text for the title is being rendered as below :
text:'test'
How to get rid of the ascii for the qutoes in javascript.
I have a graph that is properly generated when the page loads. That code is:
<body>
<div id="placeholder" style="width:800px;height:400px;"></div>
<script type="text/javascript">
$(function () {
$.plot($("#placeholder"),
[ { data: %s } ],
{ xaxes: [ { mode: 'time' } ],
yaxes: [ ] })
});
</script>
Which works fine. I have a button that executes jquery and makes a request to get a new json data structure. I've validated that the json being returned is indeed proper json. I'm attempting to graph the result with:
<script type="text/javascript">
$(function() {
$("#button").click( function()
{
//alert('button clicked');
$.ajax({
url: '/graph',
type: 'POST',
dataType: 'html',
data: {
start_date: $('#start_date').val(),
end_date : $('#end_date').val(),
ticker : $('#ticker').val()
},
success: function(result) {
var placeholder = $("#placeholder");
$.plot(placeholder,
[ { data: result } ],
{ xaxes: [ { mode: 'time' } ],
yaxes: [ ] });
}
});
}
);
});
Which redraws the graph, but it's empty and the y-axes is the default -1.0 through 1.0 and the x-axes is a single time entry of 00:00:00.
I've tried to use the setData() and draw() method calls but they don't fix the issue.
There are no javascript errors being thrown as shown by firebug.
So, what am I doing wrong?
TIA!
Are you sure the response is valid? Your dataType is 'html', so unless you're doing something with a script tag, then the response is just a string. If you're returning JSON directly, then you need to use dataType 'json'.