koolaid_Mixin_Jones
koolaid_Mixin_Jones

Reputation: 76

Ajax and Google charts. Passing PHP

exampleUsingPHP.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">

var jsonData = $.ajax({
url: "getData.php",
//dataType:"java",
async: false
//success: function(results) {alert(results);}
}).responseText;


// 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() {
alert(jsonData);
// Create our data table out of JSON data loaded from server.
var data = google.visualization.arrayToDataTable(jsonData);

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

</script>
</head>

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

<script>
</script>  
</html>

getData.php

   <?php 
   echo "[['Task', 'Hours per Day'],
   ['Work',     11],
   ['Eat',      2],
   ['Commute',  2],
   ['Watch TV', 2],
   ['Sleep',    7]
   ]";
   ?>

So my problem is the line...

var data = google.visualization.arrayToDataTable(jsonData);

When I try to pass jsonData into the arrayToDataTable(), it does not like that it is a string. What can I do to convert the string "jsonData" into valid javascript that can be used in the arrayToDataTable() function?

Upvotes: 1

Views: 4387

Answers (2)

user1978142
user1978142

Reputation: 7948

Alternatively, you could just use the function json_encode() for stress free results. Create an array of your values (of course build like the one that is needed for it to fit for google chart), then use the function. Sample Demo

PHP (getData.php)

if(isset($_POST['get_chart'])) {
    $values = array(
        array('Task', 'Hours Per Day'),
        array('Work', 11),
        array('Eat', 2),
        array('Commute', 2),
        array('Watch TV', 2),
        array('Sleep', 7),
    );

    echo json_encode($values);
    exit;
}

HTML/jQuery

<div id="chart_div" style="width: 900px; height: 500px;"></div>

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

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(load_chart_data);

function load_chart_data() {
    $.ajax({
        url: 'getData.php', // provide correct url
        type: 'POST',
        data: {get_chart: true},
        dataType: 'JSON', // <-- since youre expecting JSON
        success: function(chart_values) {
            console.log(chart_values); // take a peek on the values (browser console)
            draw_chart(chart_values); // call your drawing function!
        }
    });
}

function draw_chart(chart_values) {
    var data = google.visualization.arrayToDataTable(chart_values);
    var options = {
        title: 'Your super chart!',
        vAxis: {title: 'Hours Per Day', titleTextStyle: {italic: false}},
        hAxis: {title: 'Task', titleTextStyle: {italic: false}},
    };
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}

</script>

Upvotes: 2

spiderman
spiderman

Reputation: 11122

First you have to create a valid json. Right now, If you paste your returned String to jsonlint, you can see it is invalid json.

To check the validtity of the json object, you can use jsonlint

create json from php code - http://php.net/manual/en/function.json-encode.php

eg of valid json string:

{
    "Work": 11,
    "Eat": 2
}

var myJSONString = // your JSON string
var jsobj= JSON.parse(myJSONString);

Upvotes: 0

Related Questions