Reputation: 165
I want to make a Google Chart and I am trying to send a JSON encoded array from a PHP script to a JavaScript. The two files are as follows:
<html>
<head><title>
</title></head>
<body>
<?php
$data[0]=array('State','Values');
$data[1]=array('Correct',6);
$data[2]=array('Incorrect',3);
echo json_encode($data);
?>
</body>
</html>
This is saved as test.php
The javascript file is:
<html>
<head>
<script type="text/javascript" src="jquery-1.9.1.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(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "test.php",
dataType: "json",
async: false
}).responseText;
var data=google.visualization.arrayToDataTable(jsonData);
var options = {
title: 'My Chart'
};
var chart = new oogle.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
This is saved as test2.php.
When I run test2.php, nothing happens and the browser shows a blank screen. Where am I going wrong here? Please help.
Thanks.
Upvotes: 2
Views: 857
Reputation: 6896
test.php does not need all those html tags, just return the json. When mixing js and PHP it is sometimes a good idea to just use hardcoded values first, then have PHP create those hardcoded values when you are sure your js is joined up and working.
Upvotes: 0
Reputation: 4819
You don't need any HTML tags in your test.php
. Instead, just use:
<?php
$data[0]=array('State','Values');
$data[1]=array('Correct',6);
$data[2]=array('Incorrect',3);
header("Content-Type: application/json");
echo json_encode($data);
?>
HTML is not a part of JSON.
Upvotes: 3