JS error:Cannot read property 'length' of undefined; Debugging error in Google Charts

2,588 views
Skip to first unread message

Ravi Panchumarthy

unread,
Oct 13, 2011, 5:00:02 PM10/13/11
to google-visua...@googlegroups.com

The following code works fine as a independant page as itself. But if incorporated into my PHP web app, it throws error. How to debug if the error happens in the google chart JS ? Any suggestions will be helpful

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
   
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
   
<title>
      Google Visualization API Sample
   
</title>
 
</head>

 
<body style="font-family: Arial;border: 0 none;">
   
<div id="myGraphLabel" onclick="drawColumnChart();">
        My Column Chart
   
</div>
   
<div id="myColumnChart" style="width: 600px; height: 400px;"></div>
 
</body>

 
<script type="text/javascript" src="http://www.google.com/jsapi"></script>

 
<script type="text/javascript">
      google
.load('visualization', '1', {packages: ['corechart']});

     
function drawColumnChart() {
       
// Create and populate the data table.
       
var data = new google.visualization.DataTable();
        data
.addColumn('string', 'Task');
        data
.addColumn('number', 'Hours per Day');
        data
.addRows(2);
        data
.setValue(0, 0, 'Work');
        data
.setValue(0, 1, 11);
        data
.setValue(1, 0, 'Eat');
        data
.setValue(1, 1, 2);

       
// Create and draw the visualization.
       
new google.visualization.PieChart(document.getElementById('myColumnChart')).
            draw
(data, {title:"So, how was your day?"});
     
}  
   
</script>
</html>

Error in Chrome: It displays "Cannot read property 'length' of undefined", With a red background in the container

Error in Firefox: Throws error in Firebug console as: b[c] is undefinedhttp://www.google.com/uds/api/visualization/1.0/97e6275dc5c50efe5944ddda289e59d2/format+en,default,corechart.I.js Line 785

asgallant

unread,
Oct 14, 2011, 10:11:10 AM10/14/11
to google-visua...@googlegroups.com
That type of error usually occurs when the API is not fully loaded.  By calling drawColumnChart from an onClick event, you don't have any means of making sure the API is loaded before trying to draw it.  Try this instead: remove the onClick event from the 'myGraphLabel' div and add this to your js:

google.setOnLoadCallback(init);

function init({
    document.getElementById('myGraphLabel').onclick drawColumnChart;
}


This way, the onClick event will be registered after the API finishes loading.
Reply all
Reply to author
Forward
0 new messages