Próbuję uzyskać dane mysql przez php -> json -> ajax do moich zmiennych JS dla Chartjs. JSON wygenerowany przez php wygląda zupełnie dobrze. Niestety podczas próby pobrania danych z moich zmiennych konsola zwraca je jako niezdefiniowane.

Oto mój kod:

<?php

$con=mysqli_connect("---");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT clanarina, vakufnama, zekjat, year from payments where uid = 1");


$data = array();
foreach ($result as $row) {
  $data[] = $row;
}
$result->close();
mysqli_close($con);
print json_encode($data);
?>

JSON:

    [{"clanarina":"240","vakufnama":"12500","zekjat":"0","year":"2019"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2021"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2022"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2023"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2024"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2025"}]

JS:

$(document).ready(function(){
  $.ajax({
    url : "../../getchartdata_payments_user.php",
    type : "GET",
    success : function(data){
      console.log(data);

      var clanarinajs = [];
      var vakufnamajs = [];
      var zekjatjs = [];


      for(var i in data) {
        clanarinajs.push(data[i].clanarina);
        vakufnamajs.push(data[i].vakufnama);
        zekjatjs.push(data[i].zekjat);
      }
      console.log(clanarinajs);
      console.log(vakufnamajs);
      console.log(zekjatjs);
      var chartdata = {
        labels: ["2019", "2020", "2021", "2022", "2023", "2024","2025"],
        datasets: [
          {
            label: "Clanarina",
            backgroundColor: "#4e73df",
            hoverBackgroundColor: "#2e59d9",
            borderColor: "#4e73df",
            data: clanarinajs
          },
          {
            label: "Vakufnama",
            backgroundColor: "#aafac8",
            hoverBackgroundColor: "#2e59d9",
            borderColor: "#4e73df",
            data: vakufnamajs
          },
          {
            label: "Zekjat",
            data: zekjatjs
          },
          {
            label: "Goal",
            data: [54000, 54000, 55620, 57289, 59007, 60777, 62601],
            type: "line",
            fill: "false",
            backgroundColor: "yellow",
            borderColor: "yellow",
          }
        ]
      };

      var ctx = document.getElementById("myBarChart");

      var mybarchart = new Chart(ctx, {
        type: 'bar',
        data: chartdata,
        options: {
          maintainAspectRatio: false,
          layout: {
            padding: {
              left: 10,
              right: 25,
              top: 25,
              bottom: 0
            }
          },
          scales: {
            xAxes: [{
              time: {
                unit: 'year'
              },
              gridLines: {
                display: false,
                drawBorder: false
              },
              maxBarThickness: 25,
            }],
            yAxes: [{
              ticks: {
                min: 0,
                max: 70000,
                maxTicksLimit: 5,
                padding: 10,
                // Include a dollar sign in the ticks
                callback: function(value, index, values) {
                  return 'KM' + number_format(value);
                }
              },
              gridLines: {
                color: "rgb(234, 236, 244)",
                zeroLineColor: "rgb(234, 236, 244)",
                drawBorder: false,
                borderDash: [2],
                zeroLineBorderDash: [2]
              }
            }],
          },
          legend: {
            display: false
          },
          tooltips: {
            titleMarginBottom: 10,
            titleFontColor: '#6e707e',
            titleFontSize: 14,
            backgroundColor: "rgb(255,255,255)",
            bodyFontColor: "#858796",
            borderColor: '#dddfeb',
            borderWidth: 1,
            xPadding: 15,
            yPadding: 15,
            displayColors: false,
            caretPadding: 10,
            callbacks: {
              label: function(tooltipItem, chart) {
                var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
                return datasetLabel + ': KM' + number_format(tooltipItem.yLabel);
              }
            }
          },
        }
      });
    },
  });
});

Wyjście konsoli:

[{"clanarina":"240","vakufnama":"12500","zekjat":"0","year":"2019"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2021"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2022"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2023"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2024"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2025"}] chart-bar-demo.js:10:15

Array(385) [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, … ]
chart-bar-demo.js:22:15

Array(385) [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, … ]
chart-bar-demo.js:23:15

Array(385) [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, … ]
chart-bar-demo.js:24:15

Jak widać, console.log (dane) również działa dobrze, ale umieszczanie danych w zmiennych wydaje się być problemem.

Dzięki za pomoc !

0
dinib 8 styczeń 2020, 17:26

1 odpowiedź

Najlepsza odpowiedź

JSON zwrócony przez PHP jest nadal ciągiem znaków w punkcie, w którym wypychasz do tablic. Zauważysz, że długości tablicy odpowiadają długości ciągu.

Musisz przeanalizować ciąg JSON w tablicę JS, zanim ją zapętlisz, co możesz zrobić za pomocą JSON.parse();

0
Terminal 8 styczeń 2020, 14:34