2

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If this fixed your problem, please tick the green tick next to my answer - and welcome to Stack Overflow!
0

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.

Comments

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.