Redraw Morris Donut after AJAX call - javascript

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 .

Related

How to Stop Chart.js Rendering Over Previous Chart

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>

How to properly code Javascript / Ajax for use with Chart.js

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}

unable to create dynamic events in fullcalendar

i have a situation in which i m trying to create events dynamically using the plugin fullcalendar im trying to create events with the help of the ajax call and the data retrieved is in the form of json
when i m trying to create events only event at index 0 is getting created rest of events are not created
the javascript code is as follows
function showData()
{
var ids = showValidData();
if (ids.length != 0)
{
$.ajax({
url: $("#base-url").val() ,
type: 'POST',
data: {'ids': ids},
dataType: 'json',
success: function (response)
{
var data = response.data;
var myevents = [];
if (response.success)
{
$(data).each(function (index, value) {
myevents.push({
title: value.layoutName,
start: value.startDate,
end: value.endDate
});
});
console.log(myevents);
$(".fc-event-container").click();
$('#calendar-example-1').fullCalendar({
events: myevents,});
return;
}
}
});
}
}
Set events when initializing FullCalendar - define the url of the script that returns a json of events from your database (https://fullcalendar.io/docs/event_data/events_function/). If you want to dynamically refresh the calendar , you can add a setInterval ontop:
$(document).ready(function(){
setInterval(function(){$('#calendar').fullCalendar('refetchEvents')}, 30000);
$("#calendar").fullCalendar({
...
events: {
url: 'script.php',
type: 'POST',
data: {
data1: x,
data2: y
},
success : function(response){
// do something
},
}
});
});

Pass c3js chart options to function

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)
}

Zing feed plotting multiple series in 1 chart

I am trying to plot 2 line series data in ZingChart feed.
Below is my script code.
<script>
var chartData = {
"type":"line",
"refresh": {
"type": "feed",
"transport": "js",
"url": "feed()",
"interval": 1000
},
"series":[
{
"values":[]
},
{
"values":[]
}
]
};
window.onload = function() {
zingchart.render({
id: "chartDiv",
data: chartData,
height: 600,
width: "100%"
});
};
window.feed = function(callback) {
$.ajax({
type: "GET",
dataType: "json",
headers: {
Accept: "application/json",
"Access-Control-Allow-Origin": "*"
},
url: "/PerformanceMonitor/showProcessUsage/${processName}",
success: function (data) {
var mem = data.mem.size/100000;
var tick = {
plot0: parseInt(mem)
};
callback(JSON.stringify(tick));
var tick2 = {
plot1:parseInt(mem/1000)
};
callback(JSON.stringify(tick2));
}
});
};
It gets displayed , but looses the line nature of the graph.Is this the right way ?Is there a better method?. Later I am planning to let user decide how many plots to be allowed in chart at runtime.Is there something in ZingChart that I can make use of ?
Thanks in advance.
The tick object contains the data for each series of a plot. That means you can add multiple plots to that object.
You can replace everything in your success callback with the following code...
var mem = data.mem.size/100000;
var tick = {
plot0: parseInt(mem),
plot1: parseInt(mem/1000)
};
callback(JSON.stringify(tick));
If you wanted to add a third plot to the series, you'd just add a plot2 attribute (since ZingChart's series have a 0-based index).
I'm on the ZingChart team. Let me know if you have other questions.

Categories