1

I am working on google charts at the minute and I have got a basic one setup.

What it does at present is connects to a DB and returns a dataset based on 1 query. I am wondering is, if I want to draw more charts with different queries to the database how do I do this? Or what is the best practice?

For instance, there is already one connection with one query, how can I add another query, and then draw the charts based on what is returned?

I understand that might be a broad question, but maybe someone could show me how I would return a different query/dataset from the DB?

This is my code:

 $(document).ready(function(){

    console.log("hello world")
    //alert("result")

    $.ajax({
        url:"data.php",
        dataType : "json",
        success : function(result) {
            google.charts.load('current', {
                'packages':['corechart','bar']
            });
            google.charts.setOnLoadCallback(function() {
                console.log(result[0]["name"])
                drawChart(result);                  
            });
        }
    }); 

    //add a 2nd call - will need a 2nd draw charts to draw the different dataset assuming it will be different
    //                  - will need a 2nd data.php as the query will be different on the dataset
    $.ajax({
        url:"data.php",
        dataType : "json",
        success : function(result2) {
            google.charts.load('current', {
                'packages':['corechart','bar']
            });
            google.charts.setOnLoadCallback(function() {
                console.log(result2[0]["name"])
                drawChart(result2);                 
            });
        }
    }); 

    function drawChart(result) {

        var data = new google.visualization.DataTable();
        data.addColumn('string','Name');
        data.addColumn('number','Quantity');
        var dataArray=[];
        $.each(result, function(i, obj) {
            dataArray.push([ obj.name, parseInt(obj.quantity) ]);
        });

        data.addRows(dataArray);

        var piechart_options = {
            title : 'Pie Chart: How Much Products Sold By Last Night',
            width : 400,
            height : 300
        }
        var piechart = new google.visualization.PieChart(document
                .getElementById('piechart_div'));
        piechart.draw(data, piechart_options)

        var columnchart_options = {
            title : 'Bar Chart: How Much Products Sold By Last Night',
            width : 400,
            height : 300,
            legend : 'none'
        }
        //var barchart = new google.visualization.BarChart(document
            //  .getElementById('barchart_div'));               
        //barchart.draw(data, barchart_options)

        var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
        chart.draw(data, google.charts.Bar.convertOptions(columnchart_options));
    }           //have added this column chart but need to wrok out if it is best practice????

}); 

I am getting an object back from my DB query, but I want to know how to return more/different datasets from the same DB connection? For example what if I wanted to draw another chart with the dataset returned from this query select * from product where name="Product1" OR name="Product2";

0: Object { id: "1", name: "Product1", quantity: "2" }
​1: Object { id: "2", name: "Product2", quantity: "3" }
​2: Object { id: "3", name: "Product3", quantity: "4" }
​3: Object { id: "4", name: "Product4", quantity: "2" }
​4: Object { id: "5", name: "Product5", quantity: "6" }
​5: Object { id: "6", name: "Product6", quantity: "11" }

For what it is worth my php code is as follows:

data.php

<?php
require_once 'database.php';
$stmt = $conn->prepare('select * from product');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
echo json_encode($results); 
?>

database.php

<?php
$conn = new PDO('mysql:host=192.168.99.100;dbname=demo','root', 'root');
?>

note: this might be of interest

HattrickNZ
  • 4,373
  • 15
  • 54
  • 98

1 Answers1

2

google charts only needs to be loaded once per page load,
not every time you need to draw a chart

also, google.charts.load can be used in place of --> $(document).ready
it will wait for the page to load before executing the callback / promise

recommend setup similar to following snippet...

google.charts.load('current', {
  packages: ['corechart', 'bar']
}).then(function () {
  $.ajax({
    url: 'data.php',
    dataType: 'json'
  }).done(drawChart1);

  $.ajax({
    url: 'data.php',
    dataType: 'json'
  }).done(drawChart2);
});

function drawChart1(result) {
  ...
}

function drawChart2(result) {
  ...
}
WhiteHat
  • 59,912
  • 7
  • 51
  • 133
  • tks very helpful! the 2nd ajax call, would that have a 2nd data.php file with a different sql query, for the different dataset? the was a general Q in there re the number of ajax calls, but judging by your answer it seems increasing the ajax calls might be ok?I was possibly hoping to be more eficient there. – HattrickNZ Mar 28 '18 at 19:00
  • yes, it would be a second call, one ajax per query -- unless you build your php to run and return multiple data sets... – WhiteHat Mar 28 '18 at 19:08
  • tks, question answered. but my next question is - How do I build your php to run and return multiple data sets? I will do some research and may post/link a question here to that.tks again! – HattrickNZ Mar 28 '18 at 19:40