Chris A Chris A - 4 months ago 50
Ajax Question

Redraw Morris Donut After Ajax Call

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.

Please can someone help me? I've wasted hours on this and my deadline is fast approaching.

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:

enter image description here

Answer

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