views:

1062

answers:

7

Hello. 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.

Please help

Thanks in advance

$(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});                              
}
A: 

Have you tried doing this as a synchronous AJAX request? Notice the async setting below.

$.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']}); 
        google.setOnLoadCallback(drawData(html));                                                   
    }
}); 
James
I just tried and it didn't work =/
Curro
A: 

i am not familiar at all with the google apis, but i guess that 'html' in the callback is actually json or script, you can try the $.ajax 'dataType' option:

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

more info: http://api.jquery.com/jQuery.ajax/

dimvic
I think that's that not the problem because I do get the info from the AJAX Request. If in the success function I do an "alert(html)" I can see the info requested. Problem is that it seems that the Google API is not loading on that call. Thanks!
Curro
A: 

Looks like you're missing the Google library that provides the visualization. Are you sure you've included all the needed google scripts?

acrosman
I have this two lines in the header of my PHP file: <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript" src="lib/jquery.js"></script>I don't think that's the problem because if I do it without AJAX it works fine
Curro
Have you tried moving the visualization load ("google.load('visualization',..." ) to happen before the Ajax call?
acrosman
A: 

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.

Finbarr
+1  A: 

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);                                                   
}}); 
Darkyo
+3  A: 

Another shot in the dark :) - 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));                                                   
    }
});     

});

jamie-wilson
Actually that could make sense because your google method might not be accessible from outside the ajax request. Your error message is telling you that google.visualisation doesn't exist
jamie-wilson
Hey, this worked! thank you, I thought I had tried this before, seems that I did something wrong. Thanks!
Curro
A: 

I am using an AJAX-based tab system and Google's Interactive Line Chart Visualizations in one of my projects and ran into a similar brick wall.

Because of AJAX's inherent blocking of cross-domain scripting, you can't load the Google javascript API (http://www.google.com/jsapi) or any other external resources.

And since Google's terms of service prohibit offline (aka "not hosted on Google") use of their visualization API, you can't legally get a copy of the scripts and host them yourself as is required.

I tried a hacky workaround of including a file called "get_vis.php" instead of the "visualization_page.php" in my tabs; where the contents of "get_vis.php" is:

<?php 
echo file_get_contents('http://domain.com/path/to/visualization_page.php');
?>

But, no luck, it seems the only way to get the API to load properly is to adjust security settings so as to allow interaction with Google's servers. I don't know if it helps, but good luck.

dan