Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery load Google Visualization API with AJAX

There is an issue that I cannot solve, I've been looking a lot in the internet but found nothing.

I have this JavaScript that is used to do an Ajax request by PHP. When the request is done, it calls a function that uses the Google Visualization API to draw an annotatedtimeline to present the data.

The script works great without AJAX, if I do everything inline it works great, but when I try to do it with AJAX it doesn't work!!!

The error that I get is in the declaration of the "data" DataTable, in the Google Chrome Developer Tools I get a Uncaught TypeError: Cannot read property 'DataTable' of undefined.

When the script gets to the error, everything on the page is cleared, it just shows a blank page.

So I don't know how to make it work.

$(document).ready(function(){               
    // Get TIER1Tickets                 
    $("#divTendency").addClass("loading");

    $.ajax({
        type: "POST",
        url: "getTIER1Tickets.php",
        data: "",
        success: function(html){
            // Succesful, load visualization API and send data      
            google.load('visualization', '1', {'packages': ['annotatedtimeline']}); 
            google.setOnLoadCallback(drawData(html));                                                   
        }
    });     
});


function drawData(response){            
    $("#divTendency").removeClass("loading");

    // Data comes from PHP like: <CSV ticket count for each day>*<CSV dates for ticket counts>*<total number of days counted>
    // So it has to be split first by * then by ,
    var dataArray   = response.split("*");
    var dataTickets = dataArray[0];
    var dataDates   = dataArray[1];
    var dataCount   = dataArray[2];

    // The comma separation now splits the ticket counts and the dates
    var dataTicketArray = dataTickets.split(",");
    var dataDatesArray  = dataDates.split(",");

    // Visualization data                               
    var data = new google.visualization.DataTable();
    data.addColumn('date', 'Date');
    data.addColumn('number', 'Tickets');
    data.addRows(dataCount);                                                    

    var dateSplit = new Array();
    for(var i = 0 ; i < dataCount ; i++){
        // Separating the data because must be entered as "new Date(YYYY,M,D)"
        dateSplit = dataDatesArray[i].split("-");
        data.setValue(i, 0, new Date(dateSplit[2],dateSplit[1],dateSplit[0]));
        data.setValue(i, 1, parseInt(dataTicketArray[i]));
    }               

     var annotatedtimeline = new google.visualization.AnnotatedTimeLine(document.getElementById('divTendency'));
     annotatedtimeline.draw(data, {displayAnnotations: true});                              
}
like image 562
Arturo Avatar asked Feb 23 '10 00:02

Arturo


5 Answers

I remember when I used a Google API it explicitly said to initialize the load first off. So maybe keep the google.load function out of the AJAX, and then just keep calling the second part of your function on success:

//Straight Away!
google.load('visualization', '1', {'packages': ['annotatedtimeline']}); 

$(document).ready(function(){
    // Get TIER1Tickets                 
    $("#divTendency").addClass("loading");

    $.ajax({
        type: "POST",
        url: "getTIER1Tickets.php",
        data: "",
        success: function(html){
            // Succesful, load visualization API and send data
            google.setOnLoadCallback(drawData(html)); 
        }
    });  
});
like image 89
jamie-wilson Avatar answered Oct 29 '22 21:10

jamie-wilson


I know this is an older post, but after some digging through the google.load docs, I found an async option in case you want to dynamically load the libs:

http://code.google.com/apis/loader/

function loadMaps() {
   google.load("visualization", "2", {"callback" : function(){ alert(4); }});
}
like image 39
daxiang28 Avatar answered Oct 29 '22 20:10

daxiang28


I know this is an old thread but this might help others.
I've run into the same problem now and it is very similar (if not the same) I had earlier with a CMS:

code on page:

<div id='targetdiv'></div>
<script type="text/javascript">
$(document).ready( function () {
   $('#targetdiv').load('...some url...');
});
</script>

part of the script loaded with ajax:

<script type="text/javascript">
  document.write("hello");
</script>

The result is a page with the text "hello" that looks like it is still being loaded. This is caused by the document.write method. Since the script is loaded into an already finished and closed document, the browser opens a new one and I suppose the javascript engine is waiting for the next line of code that will never arrive as opening a new document deleted the one being executed.

like image 2
balazs Avatar answered Oct 29 '22 22:10

balazs


This is a bit of a shot in the dark:

google.setOnLoadCallback(function() { drawData(html) });

It may be that the reference to html is lost, and a closure is required.

like image 1
Finbarr Avatar answered Oct 29 '22 21:10

Finbarr


Could you provide a sample of the data returned ? You may call directly drawData(html) :

$.ajax({
type: "POST",
async: false,
url: "getTIER1Tickets.php",
data: "",
success: function(html){
    // Succesful, load visualization API and send data      
    google.load('visualization', '1', {'packages': ['annotatedtimeline']}); 
   //You are already in a callback function, better like this ? 
    drawData(html);                                                   
}}); 
like image 1
Darkyo Avatar answered Oct 29 '22 20:10

Darkyo