The clearing of the legend should probably moved into the block in line 90, where the chart area is cleared as well (`element[0].innerHTML = '';`). Otherwise, if the server returns an error or no data, you remove the legend, but not the graph.