google / google-visualization-issues

288 stars 35 forks source link

problem TypeError: google.visualization.DataTable is not a constructor #2798

Open Arafat-Thabet opened 4 years ago

Arafat-Thabet commented 4 years ago

how solve this problem it make web page error

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">

// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});

// Callback that creates and populates a data table,

// instantiates the bar and pie chart, passes in the data and
google.charts.setOnLoadCallback(
    function() { 
// Anonymous function that calls drawChart1 and drawChart2
        drawChart(20,10,30);
        drawPieChart();

      });
// draws it.
function drawChart(x=20,y=10,max=30) {

  // Create the data table.
  var bar_dataTable = new google.visualization.DataTable(); // error line
  bar_dataTable.addColumn('string' ,' ');

  bar_dataTable.addColumn('number',' ');

  bar_dataTable.addRows([
     ['total_working_days ', x],            //row
     ['total_abscence_days', y],            // row2
         // CSS-style declaration
      ]);

  // Set chart options
  var options ={
        width: 350,
        height: 380,
        'is3D':true,
        bar: {groupWidth: "60%"},

        legend: { position: "none" },
        vAxis: {
            minValue: 0,
            maxValue:max
          }
      }

  var bar_chart = new google.charts.Bar(document.getElementById('chart_attandance-div'));
  bar_chart.draw(bar_dataTable,google.charts.Bar.convertOptions(options));

}
function drawPieChart(x=20,y=10,max=30) {

var pie_dataTable = new google.visualization.DataTable();
pie_dataTable.addColumn({ type: 'string', id: 'total_att_title' });

pie_dataTable.addColumn({ type: 'number', id: 'days_num' });

pie_dataTable.addRows([
     ['total_working_days ', x],            //row
     ['total_abscence_days', y],            // row2
     // CSS-style declaration
  ]);
    var options_chart2 = {
    //  title: "حساب الدوام   ",
      width: 300,
      height: 380,
      'is3D':true,
      bar: {groupWidth: "90%"},
     legend: { position: "none" },
     pieSliceText: 'label',
      vAxis: {
          minValue: 0,
          maxValue:max
        }
    }
// Instantiate and draw our chart, passing in some options.
var chart2 = new  google.visualization.PieChart(document.getElementById('chart_div2'));

chart2.draw(pie_dataTable,options_chart2);

}
</script>
dlaliberte commented 4 years ago

Seems to work fine for me: https://jsfiddle.net/dlaliberte/tdhn1fm4/ Which browser (and version) are you using?

dhayalandeena commented 10 months ago

Same error myself also facing :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    var RC_chart;
    var rc_trend_chart;

 google.charts.load('upcoming', {packages: ['corechart', 'controls']
    }).then(drawChart_rc);

function drawChart_rc(startDate_rc, endDate_rc, data_rc) {

        RC_chart = new google.visualization.DataTable();
        RC_chart.addColumn('date', 'Date');
        RC_chart.addColumn('number', 'Repair Completed');

        var date_rc = new Date();
        var first;

        if (startDate_rc && endDate_rc) {
            first_rc = new Date(startDate_rc);
            endDate_rc = new Date(endDate_rc);
        } else {
            first_rc = new Date(date_rc.getFullYear(), date_rc.getMonth(), 1);
            endDate_rc = date_rc;
        }

        if (data_rc && typeof data_rc === 'object') {
            var dataArray = Object.entries(data_rc);

            dataArray.forEach(([dateString, jc_open], i) => {
                var dates = new Date(dateString);

                RC_chart.addRow([dates, parseInt(jc_open)]);
            });
        } else {

            console.error('Data is not in the expected format:', data_rc);
        }

        var chart_options = {
            colors: ['#de8b1f', '#464B7C'],
            title: 'No of Repair Completed',
            isStacked: true,
            // bar: {groupWidth: "95%"},
            width: '650',
            height: '280',
            legend: {
                position: 'top'
            },
            hAxis: {
                format: 'd', // Display only day number
                title: 'date'
            },
            vAxis: {

                title: 'Count'
            },
            seriesType: 'bars',
            // series: {
            //     2: {
            //         type: 'line'
            //     }
            // },
        };

        rc_trend_chart = new google.visualization.ChartWrapper({
            chartType: 'ComboChart',
            containerId: 'rc_open_trend_chart',
            options: chart_options
        });

        rc_trend_chart.draw();

        updateChart_rc(startDate_rc, endDate_rc);
    }
</script>

</script>
 function filterDateRange_rc() {

        var outlet_ID_rc = $('#outlet_rc').val();
        console.log(outlet_ID_rc);

        var selectedMonth_rc = $('#month_rc').val();
        var selectedYear_rc = $('#year_rc').val();

        if (!selectedMonth_rc) {
            selectedMonth_rc = new Date().getMonth(10) - 1;
            $('#month_rc').val(selectedMonth_rc);
        }

        if (!selectedYear_rc) {
            selectedYear_rc = new Date().getFullYear(2023);
            $('#year_rc').val(selectedYear_rc);
        }

        // Calculate start and end dates
        var startDate_rc = selectedYear_rc + '-' + selectedMonth_rc + '-01';
        //   var endDate = selectedYear + '-' + selectedMonth + '-' + new Date(selectedYear, selectedMonth, 0).getDate();

        var currentdate_rc = new Date().getDate();
        var currentYear_rc = new Date().getFullYear();
        var currentMonth_rc = new Date().getMonth() + 1;

        var endDate_rc =
            selectedYear_rc == currentYear_rc && selectedMonth_rc == currentMonth_rc ?
            currentYear_rc + '-' + ('0' + (currentMonth_rc)).slice(-2) + '-' + currentdate_rc :
            selectedYear_rc + '-' + ('0' + selectedMonth_rc).slice(-2) + '-' + new Date(selectedYear_rc, selectedMonth_rc + 1, 0).getDate();

        console.log('Start Date:', startDate_rc);
        console.log('End Date:', endDate_rc);

        $.ajax({
            url: '<?php echo $baseurl; ?>dashboards/rcChart',
            type: 'POST',
            dataType: 'json',
            data: {
                rc_from_date: startDate_rc,
                rc_end_date: endDate_rc,
                rc_outlet: outlet_ID_rc,

            },
            success: function(data_rc) {

                console.log(data_rc);

                drawChart_rc(startDate_rc, endDate_rc, data_rc);
                updateChart_rc(startDate_rc, endDate_rc);
            },
            error: function(error) {
                console.error("Error:", error);
            }
        });

    }

  function updateChart_rc(startDate_rc, endDate_rc) {
        var startDate_RC = startDate_rc ? new Date(startDate_rc) : null;
        var endDate_RC = endDate_rc ? new Date(endDate_rc) : null;

        var view = new google.visualization.DataView(RC_chart);

        if (startDate_RC && endDate_RC) {
            view.setRows(RC_chart.getFilteredRows([{
                column: 0,
                minValue: startDate_RC,
                maxValue: endDate_RC
            }
        ]));

        }

        rc_trend_chart.setDataTable(view);
        rc_trend_chart.draw();
    }
</script>    

In this above google chart code, sometimes facing the error dashboard:1862 Uncaught TypeError: google.visualization.DataTable is not a constructor

dlaliberte commented 10 months ago

Hi Deena,

It looks like you are calling drawChart_rc from your $.ajax call, which means drawChart_rc could be called before the google charts library has finished loading. If you look at the stack trace when the error occurs, you should see whether that is the case.