Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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.

share|improve this answer
 
Thank you my friend. You saved my life. You are a legend!!!! –  Benjamin Felix Apr 20 at 17:36
 
If this fixed your problem, please tick the green tick next to my answer - and welcome to Stack Overflow! –  Alfo Apr 20 at 18:47
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.