views:

206

answers:

1

I can't figure out how to load a datable using ajax/json. Here is my json code in a remote file (pie.json)

{ 
   cols: [{id: 'task',  label: 'Task',          type: 'string'}, 
          {id: 'hours', label: 'Hours per Day', type: 'number'}], 
   rows: [{c:[{v: 'Work'},     {v: 11}]}, 
          {c:[{v: 'Eat'},      {v: 2}]}, 
          {c:[{v: 'Commute'},  {v: 2}]}, 
          {c:[{v: 'Watch TV'}, {v:2}]}, 
          {c:[{v: 'Sleep'},    {v:7, f:'7.000'}]} 
         ] 
  } 

This is what I have tried so far but it doesn't work.

<script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt; 

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

function ajaxjson() { 
   jsonreq=GetXmlHttpObject(); 
   jsonreq.open("GET", "pie.json", true); 
   jsonreq.onreadystatechange = jsonHandler; 
   jsonreq.send(null); 
  } 


function jsonHandler() { 
 if (jsonreq.readyState == 4) 
   { 
   var res = jsonreq.responseText; 
   google.setOnLoadCallback(drawChart); 
   function drawChart() { 
   var data = new google.visualization.DataTable(res, 0.6) 
   var chart = new google.visualization.PieChart(document.getElementByI('chart_div')); 
   chart.draw(data, {width: 400, height: 240, is3D: true}); 
   }     // end drawChart 
   } // end if 
} // end jsonHandler 


function GetXmlHttpObject() 
  { 
   var xmlHttp=null; 
   xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
   return xmlHttp; 
  } 

Things work perfectly if I replace the 'res' variable with the actual code in pie.json.

Any help would be greatly appreciated.

A: 

Just a guess because I'm unfamiliar with the google objects you are using, but I'm pretty sure responseText just returns a string. JavaScript can't natively parse JSON (only XML to the best of my knowledge), so you'd have to eval("var res = " + jsonreq.responseText).

I hope this helps.

tau