0

I am having a slight issue rendering a chart using chart.js, pulling data from a MySQL db. It works when I am using an external file, to pull the data, However I am trying to code the entire thing on one File, but this is giving some trouble I am assuming the json_encode data is not being supplied properly the code is listed below:

<!DOCTYPE html>
<html>
<head>
<title>Demo Charts</title>  
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/Chart.min.js"></script>
    <script src="js/jquery-ui.min.js"></script>
</head>
<body>
    <div>
<?php
$conn = mysqli_connect("localhost","root","password","db1");

$sqlQuery = "SELECT student_id,student_name,marks FROM tbl_marks ORDER BY student_id";
$result = mysqli_query($conn,$sqlQuery);
$data = array();
foreach ($result as $row) {
    $data[] = $row;
}
mysqli_close($conn);
$json = json_encode($data);
?>
        <div>
            <span><h3>Pie Chart</h3></span>
            <canvas id="pieCanvas"></canvas>
        </div>
        <script type="text/javascript"> 
        $(document).ready(function () {
            showGraph2();
        });

        function showGraph2()
        {
            {
                var data = <?php echo $json; ?>;
               // $.post("api/data.php", `==>>THIS WORKS`
             $.post(data,
                function(data)
                {
                    console.log(data);
                     var name = [];
                    var marks = [];
                    var coloR = [];

                     var dynamicColors = function() {
                    var r = Math.floor(Math.random() * 255);
                    var g = Math.floor(Math.random() * 255);
                    var b = Math.floor(Math.random() * 255);
                    return "rgb(" + r + "," + g + "," + b + ")";
                 };


                    for (var i in data) {
                        name.push(data[i].student_name);
                        marks.push(data[i].marks);
                         coloR.push(dynamicColors());
                    }

                    var chartdata = {
                        labels: name,
                        datasets: [
                            {
                                label: 'Student Marks',
                                backgroundColor: '#49e2ff',
                                //borderColor: '#46d5f1',
                                backgroundColor: coloR,
                                hoverBackgroundColor: '#CCCCCC',
                                hoverBorderColor: '#666666',
                                data: marks
                            }
                        ]
                    };

                    var graphTarget = $("#pieCanvas");

                    var barGraph = new Chart(graphTarget, {
                        type: 'pie',
                        data: chartdata
                    });
                });
            }
        } 
         showGraph2();


</script>

    </div> 

</body>
</html>
Dharman
  • 30,962
  • 25
  • 85
  • 135
dames
  • 1,421
  • 8
  • 35
  • 55
  • 1
    _"I am assuming the json_encode data is not being supplied properly"_ - Don't assume... debug! Right click on the page, choose `View source` and check what the output actually is. – M. Eriksson Jul 05 '18 at 18:16
  • My correction I have been debugging and trying for the last two days, "view source" has also become my new friend in checking my updates when I am trying a new fix, however I have seen where I may need external assistance hence my post – dames Jul 05 '18 at 18:20
  • You're also not actually fetching the result from the query. Instead of your foreach-loop, just do: `$data = mysqli_fetch_all($result, MYSQLI_ASSOC)` http://php.net/manual/en/mysqli-result.fetch-all.php – M. Eriksson Jul 05 '18 at 18:21
  • When you post a question here, you need to include all the results of your debugging, or we will just waste both yours and our time asking you to do it again. – M. Eriksson Jul 05 '18 at 18:22
  • 1
    You should also look into how to use `$.post()`. The first arg suppose to be a URL, not json data. I don't even know why you have it there at all, though? You already have the data and don't need to make any request to get it? You should start from scratch and try sort one thing out one at the time. There are too many issues here. – M. Eriksson Jul 05 '18 at 18:25
  • 1
    I really don't know why you are doing `$.post(data,` (or even `$.post("api/data.php"` ... you have the data already in the javascript to use, why ajax for it? – IncredibleHat Jul 05 '18 at 18:26
  • $.post("api/data.php" is used when I am pulling the json_encode($data); from a separate file, I was saying that method works – dames Jul 05 '18 at 18:30
  • 1
    @dames Your `$.post()` will run a request for the URL `[object%20Object]`, which will obviously fail. Therefore your code does essentially nothing. You need to remove/comment the AJAX related code. –  Jul 05 '18 at 18:42
  • @MagnusEriksson data is being fetched using the `foreach`, if i should simply echo ` php echo json_encode($data);?>` all array values are shown, I am trying In resolving my issue, I guess as stated too many errors are in the script, Guess Ill do additional reading to try and get better clarity, Thanks again Guys for the pointers – dames Jul 05 '18 at 18:44

1 Answers1

0

Here's the relevant JavaScript part:

const useAJAX = false;

$(document).ready(function () {
  if (useAJAX) $.getJSON('api/data.php').then(showGraph);
  else showGraph(<?= $json ?>);
});

function showGraph(data) {
  console.log(data);
  var name = [];
  var marks = [];
  var coloR = [];
  // etc, etc
}

I have completely separated a) obtaining the data and b) processing the data. This way you can nicely switch between the two.

I have directly inserted the JSON into the script, like you did. Not super clean or good practice, but will work fine for now.

I have rewritten the AJAX part slightly, I'm using $.getJSON instead, assuming that the file doesn't require any POST parameters anyway. And I used .then(), taking advantage of the fact that jQuery AJAX methods return Promises.

Final tip: don't mix PHP and HTML/JS like that. Move all your PHP stuff to the very top, set all your variables before your first echo / plain text. Then use ?><!DOCTYPE html> to move to HTML.

  • Thank U and actually your previous comment assisted, I actually solved the problem directly before you posted the solution, Thank You again – dames Jul 05 '18 at 18:57