0

I try to make a google chart from a JSON file but i can't see the error. Here is my php that does the JSON data file. The php code works just fine it gives me this:

[["Durata pedeapsa","count"],["3","4"],["7","2"],["5","1"],["2","2"],["4","1"]]

However i cannot load it into the html.

<?php
//Oracle DB user name
$username = 'TW';

// Oracle DB user password
$password = 'TW';

// Oracle DB connection string
$connection_string = 'localhost/xe';

//Connect to an Oracle database
$connection = oci_connect(
    $username,
    $password,
    $connection_string
);

$stid = oci_parse($connection, 'SELECT to_number(substr(durata_pedeapsa,0,1)) as "pedeapsa" , COUNT(DURATA_PEDEAPSA) as "count" FROM DETINUTI group by substr(durata_pedeapsa,0,1)');
if (!$stid) {
    $e = oci_error($connection);
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$r = oci_execute($stid);
if (!$r) {
    $e = oci_error($stid);
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

# set heading   
    $data[0] = array('Durata pedeapsa','count');
    $i=1;
        while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) != false) {
            $pedeapsa = $row['pedeapsa'];
            $count = $row['count'];
            $data[$i] = array($pedeapsa,$count);
            $i = $i +1;
        }
echo json_encode($data);
oci_close($connection);
?>

And this is my html that should create the charts.

<html>
<head>
    <title>Suji</title>
    <!-- Load jQuery -->
    <script language="javascript" type="text/javascript" 
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
    </script>
    <script src="jquery.min.js"></script>
    <script src="jquery-ui.min.js"></script>
    <!-- Load Google JSAPI -->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        google.load("visualization", "1", { packages: ["corechart"] });
        google.setOnLoadCallback(drawChart);

        function drawChart() {
            var jsonData = $.ajax({
                url: "/test.php",
                dataType: "json",
                async: false
            }).responseText;

            var obj = window.JSON.stringify(jsonData);
            var data = google.visualization.arrayToDataTable(obj);

            var options = {title: 'Suji'};

            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }

    </script>
</head>
<body>
    <div id="chart_div" style="width: 900px; height: 500px;">
    </div>
</body>
</html>
Teodor O.
  • 23
  • 7
  • Why are you stringifying it? And it is bad ractice to use synchronous calls. – epascarello Jun 12 '17 at 12:17
  • I don't know how to use JSON. I have to do a project for tommorw and this is what i found on the internet. Any tips? – Teodor O. Jun 12 '17 at 12:19
  • If you stringify your JSON data, you convert readable and exploitable data, with a hierarchy, into a linear chain of characters. So this just won't work to build a chart. Also, don't use `async:false`. Ever. There's no point, it leads to a poor user experience, and it's deprecated. – Jeremy Thille Jun 12 '17 at 12:32

3 Answers3

1

Use success callback method of $.ajax() to load data to the chart and don't call JSON.stringify() as google chart accept jquery object not json string. Your drawChart() function should look like this.

function drawChart() {
    $.ajax({
    url: "/test.php",
            dataType: "json",
            success:function (res) {
                var jsonData = res.responseText;
                var data = google.visualization.arrayToDataTable(jsonData);
                var options = {title: 'Suji'};
                var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
                chart.draw(data, options);
         }
    });
} 

I hope it work and your php script return valid json.

R.K.Saini
  • 2,678
  • 1
  • 18
  • 25
0

Replace your js code with this

 <script type="text/javascript">
        google.load("visualization", "1", { packages: ["corechart"] });
        google.setOnLoadCallback(drawChart);

        function drawChart() {
            var jsonData = $.ajax({
                url: "/test.php",
                dataType: "json",
                async: false
            }).responseText;

            //var obj = JSON.parse(jsonData);
           // var data = google.visualization.arrayToDataTable(obj);
             var dataTable = new google.visualization.DataTable();
             dataTable.addColumn('string', 'Durata pedeapsa');
            dataTable.addColumn('number', 'Count');

           // dataTable.addRows([jsonData]);
            dataTable.addRows(JSON.parse(jsonData));  


            var options = {title: 'Suji'};

            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(dataTable, options);
        }

    </script>

PHP CODE

Comment this line in your php code

//$data[0] = array('Durata pedeapsa','count'); //comment this line

Also convert count value to integer

Example

$data[$i] = array($pedeapsa,(int)$count);

Now your php file data will return -

[["3",4],["7",2],["5",1],["2",2],["4",1]]
shubham715
  • 3,324
  • 1
  • 17
  • 27
0

first, recommend building the json in the format google accepts
this will allow you to create the data table directly

PHP

# set heading
$data = array();

$data['cols'] = array(
  array('label' => 'Durata pedeapsa', 'type' => 'string'),
  array('label' => 'count', 'type' => 'number')
);

$data['rows'] = array();
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) != false)
  $data['rows'][] = array('c' => array(
    array('v' => (string) $row['pedeapsa']),
    array('v' => (int) $row['count'])
  ));
}
echo json_encode($data);

next, don't need both google charts libraries

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

jsapi is an old library and should no longer be used, remove it

this only changes the load statement, see following snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  $.ajax({
    url: "/test.php",
    dataType: "json",
  }).done(function (jsonData) {
    var data = new google.visualization.DataTable(jsonData);
    var options = {title: 'Suji'};
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  });
}
WhiteHat
  • 59,912
  • 7
  • 51
  • 133