andrew
andrew

Reputation: 11

Run google visualisation (javascript) loaded via ajax

Long time listener, first time caller. Not hugely adept with ajax. Presumably I'm doing something tremendously dense here:

Trying to run a google visualisation that's returned with html from an ajax response, but even though I can see the code in firebug's xhr response, it won't run when loaded from the ajax page.

Access response2.php?var=X directly and it works perfectly, so presumably it's not a problem with the code being outputed per se.

(I've moved jsapi and google.load(visualization) between the ajax page's header and response2.php with no success either way)

ajax call

$.ajaxSetup ({
    cache: false
});

$.ajax ({
    type: "GET",
    url: "return2.php",
    data: "council=Leeds City Council",
    dataType: "html",
    success: function (responseText) { 
      document.getElementById('result').innerHTML = responseText;
    }
});

return2.php

<?php
$docKey = "0Aqk6sC3LBlfjdHUxRDIycjlSM3NvX0JCWnhxUjRUbFE";
$docQuery = $_GET['council'];
?>
<script type="text/javascript">
function drawVisualization() {
google.visualization.drawChart({
   "containerId": "councilViz",
   "dataSourceUrl": "http://spreadsheets.google.com/a/google.com/tq?key=<?php echo   $docKey; ?>",
   "query":"SELECT A,B,C WHERE A CONTAINS '<?php echo $docQuery; ?>'",
   "chartType": "Table",
   "options": {
      "width": 560,
      "height" : 200
   }
 });
}
google.setOnLoadCallback(drawVisualization);
</script>
<div id="councilViz">
<?php echo $docQuery; ?>
</div>

response2.php picks up the GET variable, runs a google spreadsheets api query and returns the following code:

ajax response

<script type="text/javascript">
  function drawVisualization() {
    google.visualization.drawChart({
   "containerId": "councilViz",
   "dataSourceUrl": "http://spreadsheets.google.com/a/google.com/tq?key=0Aqk6sC3LBlfjdHUxRDIycjlSM3NvX0JCWnhxUjRUbFE",
   "query":"SELECT A,B,C WHERE A CONTAINS 'Leeds City Council'",
   "chartType": "Table",
   "options": {
      "width": 560,
      "height" : 200
   }
 });
  }
  google.setOnLoadCallback(drawVisualization);
</script>
<div id="councilViz">
Leeds City Council</div>

Try as I might, I can't get the table to draw when the code is called by ajax. I can see the result, but nothing from the visualisation script.

Many thanks,

A

Upvotes: 1

Views: 238

Answers (1)

Jason B
Jason B

Reputation: 11

You need to create the div to insert the returned html into, use .innerHTML to insert your html into that div.

then use .appendChild to append the div to the target in the dom.

Script added by setting the innerHTML property of an element doesn't get executed.

function addScript(responseText)

    {
        var newdiv = document.createElement('div');
        newdiv.innerHTML = responseText;
        document.getElementById('target').appendChild(newdiv);
    }

Upvotes: 0

Related Questions