Chartjs-Chart.js with JSON Data on Same page not displaying

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.

Leave a comment