Dante
Dante

Reputation: 36

Invalid JSON string

Hi im trying to make a line chart for my web displaying data from my database in MysQL but i get an inavlidd JSON string error and nothing display this is my code. I'm using as example the server side code from https://developers.google.com/chart/interactive/docs/php_example

HTML

  <html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="//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 jsonData = $.ajax({
      url: "getData.php",
      dataType:"json",
      async: false
      }).responseText;


var data = new google.visualization.DataTable(); //DEFINE DATATABLE

data.addColumn('string', 'Label'); //ADD COLUMN 1
data.addColumn('number', 'Value'); //ADD COLUMN 2
console.log(jsonData);
data.addRows(jsonData); //ADD THE RECEIVED jsonData

// SET OPTIONS
var options = {'title':'REALLY PRETTY PIE CHART',
    'width':400,
    'height':300};

// Instantiate and draw THE chart
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

PHP

<?php 
include_once  'Config.php'; //configuration of my Mysql Database  
$public = 'admin'; //This variable is to select the user i want


try {

        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $gsent = $conn->prepare("SELECT estado,Hora FROM Datos Where Usuario LIKE '$public'");
        $gsent->execute();

$resultado = $gsent->fetchAll();
$resultAdoJson = json_encode($resultado);
$resulset = json_decode($resultAdoJson);
$result = array();
$i = 65;
foreach($resulset as $res) {

    $result[] = array(chr($i++), intval($res->estado));
}



print json_encode($result);
}

 catch (PDOException $pe) {

    die("Could not connect to the database $dbname :" . $pe->getMessage());

}

?>

The Mysql table only has 3 row for admin with values:

Estado Hora

This is the JSON i get from the print in the php

[{"estado":"50","0":"50","Hora":"2015-02-16","1":"2015-02-16"},  {"estado":"53","0":"53","Hora":"2015-02-16","1":"2015-02-16"},{"estado":"10","0":"10","Hora":"2015-02-16","1":"2015-02-16"}]Array

var_dump($resultado)

array(3) { [0]=> array(4) { ["estado"]=> string(2) "50" [0]=> string(2) "50" ["Hora"]=> string(10) "2015-02-16" [1]=> string(10) "2015-02-16" } [1]=> array(4) { ["estado"]=> string(2) "53" [0]=> string(2) "53" ["Hora"]=> string(10) "2015-02-16" [1]=> string(10) "2015-02-16" } [2]=> array(4) { ["estado"]=> string(2) "10" [0]=> string(2) "10" ["Hora"]=> string(10) "2015-02-16" [1]=> string(10) "2015-02-16" } } 

I know that the code display a pie chart, but because i'm a newbie with php and i dont know anything of json or javascript first i want to make the example like the one. How can i convert the result when it works into a line chart?

Upvotes: 0

Views: 2456

Answers (1)

seboettg
seboettg

Reputation: 195

Your PHP script outputs the word 'Array' next to the JSON string. Remove the line echo $resultado; from your PHP script.

EDIT: Furthermore you have to format your result set as a array of array with ['key', 'value'] structure... For example:

[
      ['Mushrooms', 3],
      ['Onions', 1],
      ['Olives', 1],
      ['Zucchini', 1],
      ['Pepperoni', 2]
]

In your case, change the PHP script (for instance) as follows:

$resultado = $gsent->fetchAll();

$result = array();
$i = 65;
foreach($resultado as $res) {

    $result[] = array(chr($i++), intval($res->estado));
}

print json_encode($result);

As you can see, I have chosen "estado" for the value and A, B, C for the labels (realized with chr($i++)).

Adapt your JavaScript:

// STORE RESPONSE OF THE AJAX REQUEST IN jsonData
var jsonString = $.ajax({
      url: "getData.php",
      dataType:"json",
      async: false
      }).responseText;

var jsonData = eval(jsonString); //create an javascript array

var data = new google.visualization.DataTable(); //DEFINE DATATABLE

data.addColumn('string', 'Label'); //ADD COLUMN 1
data.addColumn('number', 'Value'); //ADD COLUMN 2

data.addRows(jsonData); //ADD THE RECEIVED jsonData

// SET OPTIONS
var options = {'title':'REALLY PRETTY PIE CHART',
    'width':400,
    'height':300};

// Instantiate and draw THE chart
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);

The result looks like that:

The resulting pie chart

I hope that helps.

Upvotes: 1

Related Questions