This is my first post so please apologize me if it’s not that good.
This is my "area_chart.charts.php" where the Array is :
$data=array();
foreach ($result as $row) {
$chartDate = date("d/m", strtotime($row['created_at']));
$chartResultats = $row['traitements'];
$chart = array("chartResultats" => $chartResultats,"chartDate" => $chartDate);
array_push($data, $chart);
}
JSON Response: https://prnt.sc/1whxygm
I’m trying to retrieve the data to use it with Chart.JS using Ajax, but the way i’m doing it doesn’t work. Do someone have an idea how to do it?
The result i want is :
chartResultats: [10, 30, 20]
chartDate: ["16/10", "16/10", "16/10"]
I tried to use Ajax like this :
$.ajax({
url:"./inc/charts/area_chart.charts.php",
method:"GET",
success:function(data) {
console.log(data);
chartResultats = data["chartResultats"];
chartDate = data["chartDate"];
// Area Chart
var ctx = document.getElementById("chartResultats");
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: [chartDate],
datasets: [{
data: [chartResulats],
}],
and Fetch but it didn’t succeded. My chart is returning me underfined.
Can you please help me or clarify me?
Thanks in advance!
3
Answers
You do not say how you output the
$data
array to make it available to AJAX.To output
$data
as JSON, you have to end your script with,You can then use your browser to open the charts.php page and inspect the JSON output.
To have the JSON you require, however, you need something like,
The output should be like,
In the code you posted, you create at each iteration a new dictionary with one chartResultats r and one chartDate d (let us call this
{ r: 1, d: 1 }
):and then you push this object onto data, getting an array of such objects:
So your data is
[ { r: 1, d: 1 }, { r: 2, d: 2 }, ... ]
(an array of dictionaries) instead of being{ r: [ 1, 2, ... ], d: [ 1, 2, ... ] }
(a dictionary of two arrays).Note.
I think that this way, you already formatted correctly the two arrays; there is no need to format them again in the success callback. So, try
Or you can use echo
echo json_encode($data);
LSerni’s answer will probably lead to solving the issue as it addresses what I see as the most important thing missing from the premise in order to solve the issue
chart is returning undefined
.Beyond that I see that when you would get a response, in your
$.AJAX.success
function is that you are only doing a single assignment which will probably fail, becausedata.chartResultats
anddata.chartDate
are undefined. Insteaddata
is an array of objects that have bothchartResultats
andchartDate
.Therefore, one solution to produce your intended output(
) is to iterate over the data. Here is one implementation: