Redraw Google Chart after every Ajax call

前端 未结 2 608
谎友^
谎友^ 2020-12-13 10:13

When the chart loads the first time with the initial default Ajax reply, it works fine. If I add in console.log(chart_data), I see my default data, then after my submit I se

相关标签:
2条回答
  • 2020-12-13 10:40

    If you've already determined that the function isn't firing the second time by a console.log or something then you might want to try taking the params off your function and call it how Google does in their examples:

    google.setOnLoadCallback(drawChart);
    

    Your code looks fine to me but I'm not sure how setOnLoadCallback preps params as I'm not very familiar with the charts libraries.

    https://developers.google.com/chart/interactive/docs/basic_load_libs

    0 讨论(0)
  • 2020-12-13 10:45

    you should only be doing google.load once in a page. The fact that you're loading data complicates things a little bit, but not by much. I would recommend that you do the google.load once at the top of your javascript, and have load_page_data set as the callback. Then, you would call drawChart from there. The modified code would look something like the following:

    var chart_data;
    var startdate = "default";
    var enddate = "default";
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(load_page_data);
    
    function load_page_data(){
        $.ajax({
            url: 'get_data.php',
            data: {'startdate':startdate,'enddate':enddate},
            async: false,
            success: function(data){
                if(data){
                    chart_data = $.parseJSON(data);
                    drawChart(chart_data, "My Chart", "Data");
                }
            },
        });
    }
    
    function drawChart(chart_data, chart1_main_title, chart1_vaxis_title) {
        var chart1_data = new google.visualization.DataTable(chart_data);
        var chart1_options = {
            title: chart1_main_title,
            vAxis: {title: chart1_vaxis_title,  titleTextStyle: {color: 'red'}}
        };
    
        var chart1_chart = new google.visualization.BarChart(document.getElementById('chart1_div'));
        chart1_chart.draw(chart1_data, chart1_options);
    }
    
    0 讨论(0)
提交回复
热议问题