开发者

jQuery load Google Visualization API with AJAX

开发者 https://www.devze.com 2022-12-21 10:06 出处:网络
There is an issue that I cannot solve, I\'ve been looking a lot in the internet but found not开发者_开发技巧hing.

There is an issue that I cannot solve, I've been looking a lot in the internet but found not开发者_开发技巧hing.

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});                              
}


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)); 
        }
    });  
});


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); }});
}


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.


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.


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);                                                   
}}); 


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));                                                   
    }
}); 


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/


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


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.


This works for me

google.load("visualization", "1", { packages: ["corechart"] });

             var chart ;
             var data ;
             var options;
        function Change(s)
        {
              // s in json format    
              google.setOnLoadCallback(reDraw(s));
              function reDraw(s) {
                  console.log(new Function("return " + s)().length); // to test if json is right
                  data = google.visualization.arrayToDataTable(new Function("return "+s)());

                    options = {
                    title: 'Product Scanes',
                    vAxis: { title: '', titleTextStyle: { color: 'red'} }         
                };

              }         
                chart = new google.visualization.BarChart(document.getElementById('chart_div'));
                chart.draw(data, options);
        }  
        function requestDate() // cal the method when you want to draw the chart 
        {

            $.ajax({
                type: "POST", // CHANGED
               // contentType: "application/json; charset=utf-8",
                url: "something.php",
                data: {  parameters you wanna pass },
                success: function (d) { 
                Change(d);


                }
            });    
        }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号