i need help how to make php code for array data to chartjs, i use 2 table and i hope to generate array code like below
function revenueCost(year) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name=\'csrf-token\']').attr('content')
},
url: url,
data: {
year: $('#year').val(),
},
type: 'POST',
dataType: 'JSON',
success:function(data){
// console.log(data);
$('#revenue-cost').empty();
var myChart = new Chart(document.getElementById('revenue-cost'), {
type: 'bar',
data: {
labels: data.label,
datasets: [{
label: 'Revenue',
data: data.revenue,
borderWidth: 0.5,
borderColor: '#00642c',
backgroundColor: 'rgba(0,100,44,0.2)'
},{
label: 'Cost',
data: data.cost,
borderWidth: 0.5,
borderColor: '#a80e19',
backgroundColor: 'rgba(168,14,25,0.2)'
}]
},
options: {
scales: {
yAxes: [{
ticks: {beginAtZero: true}
}]
}
}
});
},
});
}
and i want to make array like this
{"label":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"revenue":[105,85,55,68,72,8,0,0,0,0,0,0],"cost":[41,32,22,23,26,3,0,0,0,0,0,0]}
and chartjs view like this
chartjs grouping month
As I see the solution could be simple:
Send a POST HTTP request to your PHP file.
Validate you have a POST request with an if sentence and isset($_POST)
Prepare or extract the data, and create an associative array like the next one:
$label_data = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
$revenue_data = [105,85,55,68,72,8,0,0,0,0,0,0];
$cost_data = [41,32,22,23,26,3,0,0,0,0,0,0];
$data = [
'label' => $label_data,
'revenue' => $revenue_data,
'cost' => $cost_data
];
echo json_encode($data);
if you have data divided between arrays just merge them with array_merge and store the result in a new variable
$label_first = ["Jan","Feb","Mar","Apr","May","Jun"];
$label_second = ["Jul","Aug","Sep","Oct","Nov","Dec"];
$label_data = array_merge($label_first, $label_second );
Finally catch the response in your $.ajax and, perform the action you want to do the data.
I hope this information could be useful for you.
I'm using PHP and SQL to produce an array which counts data with the same values and how many of those value there are which outputs a json_encode to:
{"05":4,"09":4,"19":4}
Chart.js file: (trimmed down)
// Chart
var ctx = document.getElementById("monthAbuseChart");
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["1", "2", "3"],
datasets: [{
label: "Offences",
//data: [0, 7, 5] This works
data: offences // This doesn't
}],
}
}
});
// Grab the data for offences:
var offences = []
$.ajax({
method: "POST",
url: "sql/monthabuse.php",
dataType : 'json',
success: function (result) {
//offences = result;
var offences = result;
console.log(result);
},
});
The console.log outputs {19: 4, 05: 4, 09: 4}
However, if I put offences into the data section data: offences it doesn't work?
Assuming that you want to populate the response of AJAX Call in offences variable.
There are 2 issues with your current code:
Your code to create chart is running before the AJAX Call has run. In your code you are referencing offences variable but it is not yet populated.
You have defined offences as a global Variable, which is ok. But inside the AJAX Call you are again defining a new Local Variable offences by prefixing it with var. You need to use the below code which is commented in your question to populate the Global offences var.
offences = result
One way of fixing this would be to encompass your Chart Code in a New Function and inside the success callback of AJAX, call this New Function.
//Global Variable
var offences = [];
function createMonthAbuseChart() {
var ctx = document.getElementById("monthAbuseChart");
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["1", "2", "3"],
datasets: [{
label: "Offences",
//data: [0, 7, 5] This works
data: offences // This doesn't
}],
}
}
});
}
// Grab the data for offences:
$.ajax({
method: "POST",
url: "sql/monthabuse.php",
dataType : 'json',
success: function (result) {
offences = result;
console.log(result);
createMonthAbuseChart(); //Call the Chart Create Method Here.
},
});
You must make sure that data returned by AJAX Call has the same format as the data required for chart which is [0, 7, 5]. From your question it looks your AJAX Call is returning {19: 4, 05: 4, 09: 4}. You can use the following code to convert it into [4, 4, 4]
offences = Object.values(result);
Use the above line instead of following in your AJAX Callback
offences = result;
I'm trying to use ChartJs and pull data from our Oracle database. I have followed the documentation as best I could and tried to adapt them for my oci output but I can't seem to get the data pulled.Here is my fetch array from data.php:
oci_execute($query);
$data = array();
while($row = oci_fetch_array($query, OCI_ASSOC)) {
$data[] = $row;
}
print json_encode($data);
Which outputs this:
[{"DT":"01-FEB-18","SHIFTS":"FIRST","TOTAL":"6","IP":"5","DOMESTIC":"2","P_RICO":"3","EXPORTS":"1"},{"DT":"31-JAN-18","SHIFTS":"SECOND","TOTAL":"66","DOMESTIC":"49","P_RICO":"4","EXPORTS":"13"},{"DT":"31-JAN-18","SHIFTS":"FIRST","TOTAL":"55","DOMESTIC":"30","P_RICO":"1","EXPORTS":"24"},{"DT":"30-JAN-18","SHIFTS":"SECOND","TOTAL":"52","DOMESTIC":"34","P_RICO":"10","EXPORTS":"8"},{"DT":"30-JAN-18","SHIFTS":"FIRST","TOTAL":"69","DOMESTIC":"55","P_RICO":"2","EXPORTS":"12"},{"DT":"29-JAN-18","SHIFTS":"SECOND","TOTAL":"61","DOMESTIC":"41","P_RICO":"10","EXPORTS":"10"},{"DT":"29-JAN-18","SHIFTS":"FIRST","TOTAL":"48","DOMESTIC":"43","P_RICO":"2","EXPORTS":"3"},{"DT":"28-JAN-18","SHIFTS":"SECOND","TOTAL":"53","DOMESTIC":"44","P_RICO":"1","EXPORTS":"8"},{"DT":"28-JAN-18","SHIFTS":"FIRST","TOTAL":"53","DOMESTIC":"43","P_RICO":"3","EXPORTS":"7"}]
The PHP variables that I'm concerned with are DT, SHIFTS, and TOTAL. On my index.php I have this ajax call to get the variables:
$.ajax({
url: "data.php",
method: "GET",
success: function(data) {
console.log(data);
var shifts = [];
var total = [];
var dt = [];
for(var i in data) {
shifts.push("Shift " + data[i].SHIFTS);
total.push(data[i].TOTAL);
dt.push(data[i].DT);
}
var chartdata = {
labels: shifts,
datasets : [
{
label: 'Shipments Complete',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: total
}
]
};
var ctx = $("#ships");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
when I run index.php it just says that the variables are undefined.Can anyone point out where I'm going wrong?
I'm trying to create some charts using Rickshaw, importing the data with ajax generated in php.
If I use static datas, the chart displays;
If I copy/paste the data generated in the php (from a console/log()), the chart displays;
If I try to put the datas into a variable, and use that var in the js, it just doesnt' work. :(
This is my console log of what I get from the .php :
(As I said, if I copy paste that block of code into the .js substituting the "dataOutEvo" var, the graph displays as it should. So, I don't think the data is the problem.
[
{
name: "ligne",
data: [{x:0,y:35},{x:1,y:34},{x:2,y:36},{x:3,y:35},{x:4,y:40},{x:5,y:35},{x:6,y:37},{x:7,y:40},{x:8,y:45},{x:9,y:46},{x:10,y:55},{x:11,y:63},{x:12,y:61},{x:13,y:45},{x:14,y:48},{x:15,y:49},{x:16,y:45},{x:17,y:44},{x:18,y:52},{x:19,y:43},{x:20,y:37},{x:21,y:36},{x:22,y:37},{x:23,y:34}],
color: palette.color()
},
{
name: "ligne",
data: [{x:0,y:10},{x:1,y:15},{x:2,y:13},{x:3,y:15},{x:4,y:14},{x:5,y:16},{x:6,y:17},{x:7,y:25},{x:8,y:23},{x:9,y:24},{x:10,y:25},{x:11,y:28},{x:12,y:27},{x:13,y:21},{x:14,y:23},{x:15,y:19},{x:16,y:18},{x:17,y:16},{x:18,y:15},{x:19,y:14},{x:20,y:15},{x:21,y:16},{x:22,y:15},{x:23,y:16}],
color: palette.color()
},
{
name: "ligne",
data: [{x:0,y:45},{x:1,y:49},{x:2,y:49},{x:3,y:50},{x:4,y:54},{x:5,y:51},{x:6,y:54},{x:7,y:65},{x:8,y:68},{x:9,y:70},{x:10,y:80},{x:11,y:91},{x:12,y:88},{x:13,y:66},{x:14,y:71},{x:15,y:68},{x:16,y:63},{x:17,y:60},{x:18,y:67},{x:19,y:57},{x:20,y:52},{x:21,y:52},{x:22,y:52},{x:23,y:50}],
color: palette.color()
},
{
name: "ligne",
data: [{x:0,y:10},{x:1,y:15},{x:2,y:12},{x:3,y:5},{x:4,y:9},{x:5,y:15},{x:6,y:45},{x:7,y:125},{x:8,y:345},{x:9,y:256},{x:10,y:312},{x:11,y:345},{x:12,y:299},{x:13,y:165},{x:14,y:354},{x:15,y:368},{x:16,y:254},{x:17,y:213},{x:18,y:312},{x:19,y:165},{x:20,y:54},{x:21,y:32},{x:22,y:10},{x:23,y:5}],
color: palette.color()
},
{
name: "ligne",
data: [{x:0,y:2},{x:1,y:3},{x:2,y:2},{x:3,y:1},{x:4,y:1},{x:5,y:2},{x:6,y:3},{x:7,y:15},{x:8,y:45},{x:9,y:27},{x:10,y:40},{x:11,y:42},{x:12,y:35},{x:13,y:18},{x:14,y:42},{x:15,y:40},{x:16,y:30},{x:17,y:25},{x:18,y:40},{x:19,y:20},{x:20,y:6},{x:21,y:4},{x:22,y:2},{x:23,y:1}],
color: palette.color()
}
]
And this is the js where something goes wrong :
$(document).ready(function(){
$.ajax({
url: 'dataOutEvo.php', //le fichier qui va nous fournir la réponse
success: function(data) {
var dataOutEvo = data;
console.log(dataOutEvo);
var palette = new Rickshaw.Color.Palette( { scheme: 'spectrum2001' } );
var graph = new Rickshaw.Graph({
element: document.querySelector("#chart"),
width: 960,
height: 260,
renderer: 'line',
series: dataOutEvo
});
graph.render();
}
});
});
Could anyone tell me what goes wrong ? Thank you :) Mathieu
I'm asking myself now if I shouldn't go another way, using this:
$fp = fopen('dataoutevo.json', 'w');
fwrite($fp, json_encode($js));
fclose($fp);
And this :
var palette = new Rickshaw.Color.Palette();
new Rickshaw.Graph.Ajax( {
element: document.getElementById("chart"),
width: 800,
height: 500,
renderer: 'line',
dataURL: 'dataoutevo.json',
onData: function(d) {
Rickshaw.Series.zeroFill(d);
return d;
},
onComplete: function(transport) {
var graph = transport.graph;
var detail = new Rickshaw.Graph.HoverDetail({ graph: graph });
}
} );
But it's is still not working … Does anyone can help me and tell me what I'm doing wrong ?
Using your first implementation should work fine. I think your problem is when you call:
success: function(data) {
The data variable returned from PHP is actually a string (You can check this using the Javascript function) -
console.log(typeof(data));
On your PHP code you should be returning an (Associative) Array and make sure you're using the json_encode() function -
echo json_encode($output);
And on your JS side cast your returned data using the JSON.parse method -
var json_data = JSON.parse(data);
Hope that helps!
In your first implementation, add a dataType to the ajax call.
This should work fine:
$(document).ready(function(){
$.ajax({
url: 'dataOutEvo.php', //le fichier qui va nous fournir la réponse
dataType: 'json',
success: function(data) {
var dataOutEvo = data;
console.log(dataOutEvo);
var palette = new Rickshaw.Color.Palette( { scheme: 'spectrum2001' } );
var graph = new Rickshaw.Graph({
element: document.querySelector("#chart"),
width: 960,
height: 260,
renderer: 'line',
series: dataOutEvo
});
graph.render();
}
});
});
Notice the dataType: 'json' in the $.ajax call.
According to the JQuery documentation, adding the json dataType,
Evaluates the response as JSON and returns a JavaScript object. The
JSON data is parsed in a strict manner; any malformed JSON is rejected
and a parse error is thrown
I am using ajax to connect to a PHP script and then retrieve the graph coordinates needed for the jqplot jQuery graphing library.
The problem is that I am having difficulties constructing a proper PHP array that can then be converted into a jQuery array that jqplot can read.
Here is the code that retrieves the array from the PHP file:
$.ajax({
type: 'POST',
dataType: "json",
url: "behind_curtains.php",
data: {
monthSelected: month_option_selected
},
success: function (data) {
var stored_data = data;
alert(stored_data);
}
});
return stored_data;
}
Here is the code that creates the jqplot
jQuery.jqplot('chartdiv-data', [], {
title: 'Plot With Options',
dataRenderer: stored_data,
axesDefaults: {
labelRenderer: jQuery.jqplot.CanvasAxisLabelRenderer
},
axes: {
xaxis: {
label: "Day",
},
yaxis: {
label: "data"
}
}
});
If you could please help me create the proper data array in the behind_curtains.php file it would be great!
Edit 1
the graphing coordinates array should be in the form of:
[[[1,2],[3,5],[5,13]]]
and basically I need to somehow write php code that can output an array that stores data in that form.
Thanks
Solution:
*behind_curtains.php*
I put together an array that simply generates a string in the form of [[1,2],[3,5],[5,13]]. I then stored the string in a variable and echoed that variable in the form of:
echo json_encode($stored_data);
On the user side of things here is how my code looked like:
<script type="text/javascript">
$("document").ready(function() {
$.ajax({
type: 'POST',
dataType:"json",
url: "behind_curtains.php",
data: {
monthSelected: month_option_selected},
success: function(data){
var stored_data = eval(data) ;
/* generate graph! */
$.jqplot('chartdiv-weight', [stored_data], {
title: month,
axesDefaults: {
labelRenderer: jQuery.jqplot.CanvasAxisLabelRenderer
},
axes: {
xaxis: {
label: "Day",
},
yaxis: {
label: "data"
}
}
});
}
});
}
}});</script>
I hope that helps, if no, whoever is interested please let me know.
You can return the stored_data but you need to have it declared before the AJAX call, like shown in the bottom most example, here. You must also use: async: false otherwise you cannot return your data in this fashion. For the same reason if you like you could use getJSON() instead.
As it goes to formatting your retrieved data a similar issue I answered here. You need to build your array accordingly to represent your data.
If you can show how exactly does your JSON look like then I could give you a more precise answer.