通过AJAX将PHP表单变量传递给Google Chart

时间:2014-11-23 23:51:10

标签: javascript php ajax json google-visualization

我在数据库中有一个表格名称的PHP表格下拉列表,用于发布用户所做的选择。我想使用该发布的表名来生成Google图表。我无法将通过AJAX传递的变量发送到我的PHP脚本,该脚本为Google图表生成JSON。

我知道我的JSON格式正确,我只需要将已发布的表名传递给生成JSON对象的PHP脚本。

以下是显示图表的页面上的javascript代码:

<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() {

  //this is where I save the posted url parameter, format is tableDDL=tableName
  var url = <?php echo json_encode($_POST) ?>;

  var jsonData = $.ajax({
      url: "getData.php",
      type: "POST",
      data: ({url: tableDDL}),
      dataType:"json",
      async: false
      }).responseText;

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

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 400, height: 240});
}

</script>

这是我的PHP脚本,它生成JSON对象:

<?php 

include 'dbConnect.php';

$table = $_POST['url'];

$sql = "SELECT row1, row2 from " . $table;

$array = array();

$array['cols'][] = array("id" =>"", "label" => "Row1", "pattern" => "", 'type' => 'string');
$array['cols'][] = array("id" =>"", "label" => "Row2", "pattern" => "", 'type' => 'number');

if ($result = $conn->query($sql)) {
    while ($row = $result->fetch_assoc()) {
        $array['rows'][] = array('c' => array( array('v' => $row["row1"]), array('v' => $row["row2"])));
    }
}

echo json_encode($array);

?>

编辑:我已将我的代码更新为静态值,我试图将其传递给我的PHP脚本。代码仍然无效。

我的错误JSQL ajax error: parsererror, SyntaxError: Unexpected token <

以下是我一直在尝试更新的JavaScript:

<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 jsonData = $.ajax({
    url: "getData.php",
    type: "POST",
    data: '{table: tableDDL}',
    dataType:"json",
    async: false,
      success: function(response, textStatus, jqXHR){ 
          },         
      error: function(jqXHR, textStatus, errorThrown){             
          console.log("JSQL ajax error: " + textStatus + ", " + errorThrown);
          }, 
      complete: function(){
          }

    }).responseText;

  var jsonChartData = $.parseJSON(jsonData);
  console.log("jsonChartData: " + jsonChartData);

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

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 400, height: 240});
}

</script>

这是更新的PHP,应该从AJAX函数调用并获取传递的数据:

<?php

include 'dbConnect.php';

$table = $_POST['tableDDL'];

$sql = "SELECT row1, row2 from " . $table;

// check connection
if ($conn->connect_errno) {
    printf("Connect failed: %s\n", $conn->connect_error);
    exit();
}

$array = array();

$array["cols"][] = array("id" =>"", "label" => "Row 1", "pattern" => "", "type" => "string");
$array["cols"][] = array("id" =>"", "label" => "Row 2", "pattern" => "", "type" => "number");

if ($result = $conn->query($sql)) {
    while ($row = $result->fetch_assoc()) {
        $array["rows"][] = array("c" => array( array("v" => $row["row1"]), array("v" => $row["row2"])));
    }
}

echo json_encode($array);

?>

2 个答案:

答案 0 :(得分:1)

您可以查看我的代码,无问题地工作并解决调整大小问题:

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

function drawChart() {
    //All Students
    var formDataAll = {type:"All"};
    var jsonDataAll = $.ajax({
        type: "POST",
        data : formDataAll,     
        url: "./content/statisticsData.php",
        dataType:"json",
        async: false
    }).responseText;

    var dataAll = new google.visualization.DataTable(jsonDataAll);  

    var optionsAll = {
        legend: 'none',
        chartArea: {'width': '100%', 'height': '100%'},
        colors: ['#FF8615', '#68AD12', '#A22979', '#1D63BB', '#D72D16']
    };

    function resize () {
        var chartAll = new google.visualization.PieChart(document.getElementById('Allchart'));
        chartAll.draw(dataAll, optionsAll);
    }
    window.onload = resize();
    window.onresize = resize;       
}
</script>

如果你的阵列是正确的,这必须有效。

这是另一部分(statisticsData.php)(更新):

if (isset($_POST["type"])) {
    if ($_POST["type"] == "All") {
       $levelstatistics = returnstudentsstatistics();
       $array = array();
       $cols = array();
       $rows = array();
       $cols[] = array("id"=>"","label"=>"Level","pattern"=>"","type"=>"string");
       $cols[] = array("id"=>"","label"=>"Number","pattern"=>"","type"=>"number");  
       foreach ($levelstatistics as $levelstatisticsData) {
          $rows[] = array("c"=>array(array("v"=>$levelstatisticsData[0],"f"=>null),array("v"=>(int)$levelstatisticsData[1],"f"=>null)));
       }
       $array = array("cols"=>$cols,"rows"=>$rows);
       echo json_encode($array);
    } else {
        echo "Error";
    }
}

这是json输出:

{
    "cols":[
        {"id":"","label":"Level","pattern":"","type":"string"},
        {"id":"","label":"Number","pattern":"","type":"number"}
    ],
    "rows":[
        {"c":[{"v":"Lactantes","f":null},{"v":0,"f":null}]},
        {"c":[{"v":"Maternal","f":null},{"v":4,"f":null}]},
        {"c":[{"v":"Kinder","f":null},{"v":23,"f":null}]},
        {"c":[{"v":"Primaria","f":null},{"v":52,"f":null}]},
        {"c":[{"v":"Secundaria","f":null},{"v":31,"f":null}]}
    ]
}

这是db函数:

/**************************
Return students statistics
**************************/
function returnstudentsstatistics() {
    include ("./businesslogic/dbconnection/cfg.php");
    try {
        $db = new PDO('mysql:host='.$server.';dbname='.$db,$db_user,$db_password);
        $string = ""; //Your query Here"
        $sql = $db->prepare($string);               
        $sql->execute();
        $row = $sql->fetchAll();
        $db = null;
        return $row;
    } catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
    }
}

答案 1 :(得分:1)

如果JSON格式正确,则需要传递一个字符串。所以

data: ({url : tableDDL})

变为

data: '{'+url+': tableDDL}'

然后你的ajax调用看起来像这样

var jsonData = $.ajax({
  url: "getData.php",
  type: "POST",
  data: '{'+url+': tableDDL}',
  dataType:"json",
  async: false,
    success: function(response, textStatus, jqXHR){ 
        },         
    error: function(jqXHR, textStatus, errorThrown){             
        console.log("JSQL ajax error: " + textStatus + ", " + errorThrown);
        }, 
    complete: function(){
        }

  }).responseText;