php - 使用 json 和 $_GET 和 $_POST 方法的 Google CHARTS

标签 php mysql post get google-visualization

我需要一些帮助,我正在使用谷歌图表 API,但是当我尝试使用 POST 和 GET 获取一些参数时,它不会绘制图表。

如何改进代码来完成任务?

提前致谢

sql查询:

SELECT answers,COUNT(*) as count FROM surveys
where company_area ='human resources' and date >= '2014-11-01' and 
date <= '2014-12-31'GROUP BY answers ORDER BY count DESC

运行查询后phpmyadmin的结果。

Answers   count(*)
YES         23
NO           1

json 输出。

 {"cols":
         [ {"label":"Answers",
            "type":"string"},{"label":"Answers","type":"number"}],
 "rows":[
         {"c":[{"v":"YES"},{"v":23}]},
         {"c":[{"v":"NO"},{"v":1}]
         }]}

get_json.php

  <?php

$con = mysql_connect('localhost', 'root', '') or die('Error connecting to server');

mysql_select_db('sistema_encuestas', $con); 



$q = $_GET['q'];
$a = $_GET['a'];


// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
$query = mysql_query("SELECT areas_evaluacion.nombre_area, AVG(encuestas.respuestas) AS Promedio
FROM encuestas
INNER JOIN areas_evaluacion on areas_evaluacion.id = encuestas.id_area_evaluacion
WHERE encuestas.fechaentrevista>='".$q."' and encuestas.fechaentrevista<='".$a."'
Group by encuestas.id_area_evaluacion


");


$table = array();
$table['cols'] = array(

    array('label' => 'respuestas', 'type' => 'string'),

    array('label' => 'Respuestas', 'type' => 'number')
);

$rows = array();
while($r = mysql_fetch_assoc($query)) {
    $temp = array();
    // each column needs to have data inserted via the $temp array
    $temp[] = array('v' => $r['nombre_area']);
    //$temp[] = array('v' => (int)$r['id_area_evaluacion']);
    $temp[] = array('v' => (float)$r['Promedio']); // typecast all numbers to the appropriate type (int or float) as needed - otherwise they are input as strings

    // insert the temp array into $rows
    $rows[] = array('c' => $temp);
}

// populate the table with rows of data
$table['rows'] = $rows;

// encode the table as JSON
$jsonTable = json_encode($table);

// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

// return the JSON data
echo $jsonTable;
?>

chart.php

 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
     <script type="text/javascript">


         // Load the Visualization API and the piechart package.
            google.load('visualization', '1', {'packages':['corechart']});

            // Set a callback to run when the Google Visualization API is loaded.
            google.setOnLoadCallback(drawChart);

            function drawChart(num,num2) {
                var json = $.ajax({
                    url: 'get_json_areas_por_dia.php', // make this url point to the data file
                    dataType: 'json',
                     data: "q="+num ,"a="+num2,
                    async: false

                }).responseText;

                // Create our data table out of JSON data loaded from server.
                var data = new google.visualization.DataTable(json);
                var options = {
                    title: 'Estadísticas por Áreas Por dia',
                    is3D: 'true',
                    width: 800,
                    height: 600
                };
                // Instantiate and draw our chart, passing in some options.
                //do not forget to check ur div ID
                var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
                chart.draw(data, options);


            }
        </script>

  </head>
  <body>


        <form>
        <input type="date" name="date1" onchange="drawChart(this.value)">
        <input type="date" name="date2" onchange="drawChart(this.value)">
  <select name="users" onchange="drawChart(this.value)">

  </form>

        <div id="chart_div"></div>
  </body>
</html>

最佳答案

我通过在 json url 中添加缺少的 ' 来修复它

PHP

echo ' {"cols":
         [ {"label":"Answers",
            "type":"string"},{"label":"Answers","type":"number"}],
 "rows":[
         {"c":[{"v":"YES"},{"v":23}]},
         {"c":[{"v":"NO"},{"v":1}]
         }]}';

HTML

<!DOCTYPE HTML>
<html>
  <head>      
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
  <title></title>
  </head>
  <body>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
            // Load the Visualization API and the piechart package.
            google.load('visualization', '1', {'packages':['corechart']});

            // Set a callback to run when the Google Visualization API is loaded.
            google.setOnLoadCallback(drawChart);

            function drawChart() {
                var json = $.ajax({
                    url: 'get_json.php', // make this url point to the data file
                    dataType: 'json',
                    async: false,
                    type: 'GET'
                }).responseText;

                // Create our data table out of JSON data loaded from server.
                var data = new google.visualization.DataTable(json);
                var options = {
                    title: 'My Weekly Plan',
                    is3D: 'true',
                    width: 800,
                    height: 600
                };
                // Instantiate and draw our chart, passing in some options.
                //do not forget to check ur div ID
                var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
                chart.draw(data, options);

                setInterval(drawChart, 500 );
            }
        </script>  
        <div id="chart_div"></div>
  </body>
</html>

关于php - 使用 json 和 $_GET 和 $_POST 方法的 Google CHARTS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27949207/

相关文章:

来自 PHP 的 JavaScript(带有 Ajax)和输出缓冲

mysql - 在 cakephp 路由中使用 - 删除 url 的空白?

javascript - 表单发布不接受链接

Python POST 二进制数据

PHP - 如何在索引页上打印登录表单上的错误?

php - xDebug 和 PHPUnit 的代码覆盖率说是 100%,实际上不是

php - 从 json 中提取变量

MySQL 表作为 FIFO/队列

mysql - 测试多个用户是否在同一组中

php $_POST方法获取textarea值