简体   繁体   中英

Displaying a Google Chart only when data is present

I have a Google Line Chart that uses SQL data. However, when 0 rows are returned by the query, it displays a big empty chart on the page. I would like to instead display some text saying that there is no data. I tried wrapping the chart functions inside another function that I call if data is present, but nothing was displayed, even if the data was present. Here is some of my code:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function displayChart()
{
    $(document).ready(function()
    {
        google.setOnLoadCallback(drawChart);
    });
}
function drawChart() 
{
// Here we tell it to make an ajax call to pull the data from the .json file
    var jsonData = $.ajax({
    url: "Data.json",
    dataType:"json",
    async: false
}).responseText;

// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);

// Options for the graph, we set chartArea to get rid of extra whitespace
var options = {
                'width':1300,
                'height':500,
                'chartArea': {top:'10%', left:'5%', height:'75%', width:'85%'}
              };

// Instantiate and draw our chart, passing in some options and putting it in the chart_div.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options); 
}
</script>
<?

...

if($got_data == true)
{
    displayChart();
}
else
    echo "There is no data";

Any idea on what I am doing wrong, or a better way to accomplish this? Thanks in advance!

As Serg's comment says, you need to set whether display your chart in a callback from your ajax call. This is because the data that will be returned from your ajax call is not present nor accessible when you call $.ajax() . If you look down on the JQuery AJAX page you will see several examples of how to deal with your data from the ajax call, but what you are looking for will be something like the following:

$.ajax({
    url: "Data.json",
    dataType:"json",
    async: false
}).complete(function(data) {
    if (data) {
        // draw chart
    } else {
        // say no data
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM