3

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

?>

2 Answers 2

1

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/>";
    }
}
Sign up to request clarification or add additional context in comments.

14 Comments

So using your code, how are you accessing the passed data in your PHP script? $_POST['type'];?
Hi manalishi, you have an error in the sintax of the array, please take a look to the last example in post in the first answer.
I don't see the error. I have used the PHP to generate the JSON for a chart successfully before, the only thing that has changed is now I am trying to pass a variable in.
In you logi , in the while bucle, a pair of brackets are missing, use the last part of the code i post and compare the value of the Json.
My chart displays properly if I link directly to the JSON. I get the same results if I use your code to generate the JSON. I'm not able to generate the JSON because I am not able to pass a variable to the PHP script that modifies my SQL query.
|
1

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;

6 Comments

printing out the contents of ajaxData gives [object Object]
@manalishi It might be useful to trap for event and evaluate returned properties. Do you know if you getting and error response?
not sure, I'll lookup how to do that. -edit: i see your code. will check
@manalishi So sorry. To many things at once. Exact opposite: Pass string not object. This should solve.
@manalishi Also added code in Ajax call for trapping success, error, complete.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.