6

I have several AmStockCharts on the page. Those are line graphs. The data gets fetched from MySQL DB in JSON format. If user clicks on a graph dot (a bullet) then a form gets showed up where user can modify the data and save it. In this case I would need to redraw the chart and I can't figure this out.

Here is the piece of code:

//drawing all charts there are
var chart;
$.getJSON('stats.php', function (data) { // get all data from all stats at once
    var i=0;
    for (chartData in data) {
        i++;
        chart = new AmCharts.AmStockChart();
        var dataSet = new AmChart.DataSet();
        dataSet.dataProvider = chartData;
        // etc. etc. here are all the single graph parameters
        $('#stats').append('<div id="chartdiv' + i + '"></div>');
        chart.write("chartdiv" + i);
    }
});

I get all charts drawn fine. But here are two problems then. First problem that I can't access them later as the 'chart' variable refers only to the last chart drawn. The second problem is that even if I try to redraw this last chart I get no result.

To redraw the chart I have tried the following:

function chart_redraw(stat) {
    $.getJSON('stat.php?redraw=' + stat, function (data) { // get data for one particular stat
    var dataSet = new AmCharts.DataSet();
    dataSet.dataProvider = data;
    ...
    chart.dataSets = [dataSet];

    var stockPanel = new AmChart.StockPanel();
    stockPanel.validateData();
    chart.panels = [stockPanel];

    chart.validateNow();
});

That didn't do anything, i.e. the chart does not get re-drawn.

The only thing I could do is to store the chart div in a hidden input at click event by:

function chartClick (event) {
    var chartdiv = event.event.target.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id
    $('#chart_n').val(chartdiv);
    ...
}

and then use it to remove the chart from that div and crate new one at that place but it is much slower then the validateData() would be.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user164863
  • 580
  • 1
  • 12
  • 29

1 Answers1

6

When data is changed, all you need to do is set new data for data set:

dataSet.dataProvider = yourDataArray;

and then call

stockChart.validateData();

However your code should also change panel/dataset, so It's a bit strange for me. Do you get any console errors? In case not, I'd need to see full working source of your case., but I hipe my suggestion will work.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
zeroin
  • 5,863
  • 6
  • 31
  • 42
  • Ok, I couldn't make the whole thing but I made a simple code with two data sources which supposedly change at the a buttion click, evetually the graph should re-draw but it doesn't. Here it is: http://jsfiddle.net/33SDv/2/ – user164863 Oct 28 '13 at 10:58
  • 3
    You should also set chart.mainDataSet = dataSet; as it remembers previous data set and uses it. – zeroin Nov 04 '13 at 08:15