简体   繁体   中英

Pass PHP form variables to Google Chart through AJAX

I have a PHP form drop down list of table names in a database that posts the selection made by the user. I want to use that posted table name to generate a Google chart. I am having trouble getting the variable passed through AJAX to my PHP script that generates the JSON for the Google chart.

I know my JSON is formatted correctly, I just need the posted table name to get passed to the PHP script that makes the JSON object.

Here is the code for the javascript on the page that displays the chart:

<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>

And here is my PHP script that generates the JSON object:

<?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);

?>

Edit : I have updated my code to a static value that I am trying to pass through to my PHP script. The code still does not work.

My error is : JSQL ajax error: parsererror, SyntaxError: Unexpected token <

Here is the updated javascript that I have been trying:

<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>

And here is the updated PHP that should be called from the AJAX function and get the passed data:

<?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);

?>

You can take a look into my code, works without problems and solve the resize issue:

<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>

If you array is correct this must work.

This is the other part (statisticsData.php) (Updated):

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";
    }
}

This is the json output:

{
    "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}]}
    ]
}

This is the db function:

/**************************
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/>";
    }
}

If the JSON is properly formed you need to pass a string. So

data: ({url : tableDDL})

Becomes

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

and then your ajax call looks like this

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;

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