how to combine to array for chartjs width php - php

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.

Related

ChartJS and Ajax calls

I would like to make charts using ChartJS and PHP ( Silex Framework )
This is my ajax call
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
dataDossierRepartitionType=output;
},
error: function () {
alert("Oops there is an error.");
}});
This is my PHP function which i managed to call
public function dossier(){
$stmt = "SELECT count(*) FROM dossier GROUP BY typedossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_NUM);
return ?????
}
And here is my chart :
var ctx = document.getElementById("myChart");
ctx.width = 400;
ctx.height = 400;
data = {
datasets: [{
data: [dataDossierRepartitionType, 20],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
],
borderColor: [
'white',
'white',
],
borderWidth: 1
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Blue',
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
legend: {
labels: {
fontColor: "white",
fontSize: 18
}
},
maintainAspectRatio: false,
responsive: false
}
});
Route.php
$app->post('/stats', function () use ($app) {
session_start();
if(isset($_POST['method']) && !empty($_POST['method'])) {
$method = $_POST['method'];
switch($method) {
case 'dossierRepartitionType' :
$dossiers=$app['dao.dossier']->dossierRepartitionType();
break;
}
}
return new ResponseSilex("$dossiers");
});
So my AJAX call the route and then get the result of the function into $dossiers which is ouput in the Reponse, am i doing it right ?
How can i return an array with all the datas value for each count ?
I struggle to catch error and to find a proper way to bind MYSQL count value to my chart
Thank you
The main idea is that you should format your data in your model, then return JSON to the front end via json_encode. After that, you would parse the json in your ajax returns and then pass the appropriate data to the chart.
it's very easy, you need to modify your php code like this:
public function dossier(){
$stmt = "SELECT count(*) as total FROM dossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$number_of_rows = $rows->fetchColumn();
return json_encode(["total" => $number_of_rows]);
In your ajax petition you are specifying a "json" return so in your script php need's return a json.
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
dataDossierRepartitionType=output.total;
},
error: function () {
alert("Oops there is an error.");
}});
You should to receive a json from php with this structure
{total: rows_total}
so in your ajax response you'll receive that answer and you can get the data like this:
dataDossierRepartitionType=output.total;
Sorry for my english, hope can help you
You can send JSON data from php
Try this:
Php:
public function dossier(){
$stmt = "SELECT count(*) FROM dossier GROUP BY typedossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_NUM);
exit(json_encode(array('counts' => $rows)));
}
After ajax successfully complete you need to initialize chart plugin inside success callback like below:
Ajax:
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
if (output.counts) {
dataDossierRepartitionType=output.counts.join();
alert(dataDossierRepartitionType)
initCharts(dataDossierRepartitionType);
}
},
error: function () {
alert("Oops there is an error.");
}});
Finally wrap chart initialization code inside callback function
Chart:
function initCharts(dataDossierRepartitionType){
var ctx = document.getElementById("myChart");
ctx.width = 400;
ctx.height = 400;
data = {
datasets: [{
data: [dataDossierRepartitionType, 20],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
],
borderColor: [
'white',
'white',
],
borderWidth: 1
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Blue',
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
legend: {
labels: {
fontColor: "white",
fontSize: 18
}
},
maintainAspectRatio: false,
responsive: false
}
});
}

how can I modify my function via ajax?

well, to start I used to make my JSON function, but when I wanted add data I couldn't. So How can I my json function ? i'm using getJSON but I can't add data like ajax then how could I change it to ajax style. it's for hightchart
$(function() {
var processed_json = new Array();
$.getJSON('../controllers/chart_controller.php', function(data){
for (i = 0; i < data.length; i++){
processed_json.push([data[i].key,data[i].value]);
}
//draw chart
$('#salesChart').highcharts({
chart: {
type: "column"
},
title: {
text: "Best selling product"
},
xAxis: {
type: 'category',
allowDecimals: false,
title: {
text: ""
}
},
yAxis: {
title: {
text: "Scores"
}
},
series: [{
name: 'Sales',
data: processed_json
}]
});
});
});

Ajax with HighCharts setData on Symfony 2

I have a problem on my HighCharts graph with JSON data. To explain a litle bit : I have a form, when I submit this form I send my data to my controller with Ajax, I treat them and I return the new array of data for my highcharts graph, but when I use setData function with my new array the graph disappear and the new data aren't displayed.
Here is my ajax function and my test to set the new data into my graph :
$('#gestion .l-gestion-content-form #form-add-informations .btn-validation').click(function(e) {
e.preventDefault();
var chart = $('#hightchart-graf').highcharts();
var dataActionForm = $('#form-add-informations').attr('action').split("/");
var url_ajax = Routing.generate('gestion_view', { dossier: dataActionForm[4], fille: dataActionForm[5] });
var formData = $('#form-add-informations').serializeArray();
$.ajax({
type: "POST",
dataType: 'json',
url: url_ajax,
data: formData,
success: function(msg)
{
console.log(msg['infosArray']);
var test = [ msg['infosArray'].join(',') ];
console.log(test);
console.log('---------------------------------------------');
console.log(msg.infosArray);
var test2 = msg.infosArray.join(',');
var test3 = test2.replace('"', '');
console.log(test2);
chart.series[0].setData( [ msg.infosArray.join(',') ] );
//[ {{ msg.infosArray | join(',') }} ]
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('ERROR');
}
});
});
All my data are stored in the array named msg.infosArray or msg['infosArray'] and the first console.log return an array like this :
["[Date.UTC(2015,11,23),80.00]", "[Date.UTC(2015,11,23),89.00]", "[Date.UTC(2015,11,25),150.00]", "[Date.UTC(2015,11,28),45.00]", "[Date.UTC(2015,11,29),169.00]", "[Date.UTC(2015,11,29),189.00]", "[Date.UTC(2015,11,29),196.00]", "[Date.UTC(2015,11,29),200.00]", "[Date.UTC(2015,11,29),205.00]", "[Date.UTC(2015,11,30),210.00]", "[Date.UTC(2015,11,31),225.00]", "[Date.UTC(2016,0,1),250.00]", "[Date.UTC(2016,0,2),25.00]", "[Date.UTC(2016,0,3),259.00]", "[Date.UTC(2016,0,5),25.00]", "[Date.UTC(2016,0,6),250.00]", "[Date.UTC(2016,0,7),25.00]", "[Date.UTC(2016,0,8),250.00]", "[Date.UTC(2016,0,9),25.00]", "[Date.UTC(2016,0,10),250.00]", "[Date.UTC(2016,0,11),25.00]", "[Date.UTC(2016,0,12),250.00]", "[Date.UTC(2016,0,25),25.00]", "[Date.UTC(2016,0,26),250.00]"]
So I tried to escape " and ' or to join the array but nothing work. Somebody know how can I set the new data, or where I commited a fault ?
Maybe i got a bad response from my Controller ?
Thanks
You need to convert string of javascript code to array of javascript.
I wrote a demo version which converts string to javascript code. and draws chart as expected. Do not focus on the labels it's a dummy data.
JSFiddle Demo
$(function () {
var data = ["[Date.UTC(2015,11,23),80.00]", "[Date.UTC(2015,11,23),89.00]", "[Date.UTC(2015,11,25),150.00]", "[Date.UTC(2015,11,28),45.00]", "[Date.UTC(2015,11,29),169.00]", "[Date.UTC(2015,11,29),189.00]", "[Date.UTC(2015,11,29),196.00]", "[Date.UTC(2015,11,29),200.00]", "[Date.UTC(2015,11,29),205.00]", "[Date.UTC(2015,11,30),210.00]", "[Date.UTC(2015,11,31),225.00]", "[Date.UTC(2016,0,1),250.00]", "[Date.UTC(2016,0,2),25.00]", "[Date.UTC(2016,0,3),259.00]", "[Date.UTC(2016,0,5),25.00]", "[Date.UTC(2016,0,6),250.00]", "[Date.UTC(2016,0,7),25.00]", "[Date.UTC(2016,0,8),250.00]", "[Date.UTC(2016,0,9),25.00]", "[Date.UTC(2016,0,10),250.00]", "[Date.UTC(2016,0,11),25.00]", "[Date.UTC(2016,0,12),250.00]", "[Date.UTC(2016,0,25),25.00]", "[Date.UTC(2016,0,26),250.00]"];
//t = t.map(function(element){return eval(element);});
data = data.map(function (e) {
return eval(e);
});
data = data.map(function (e) {
return [(new Date(e[0])).toLocaleString(), e[1]]
});
var categories = data.map(function (e) {
return (new Date(e[0])).toLocaleString()
});
// t[0] = [date = new Date(t[0])];
$('#container').highcharts({
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldClimate.com',
x: -20
},
xAxis: {
categories: categories
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Tokyo',
data: data
}]
});
});

Extjs Don't load Grid. PHP

Somebody would helpme with this code:Grid dont load infomations.
Below is the code I'm using, but the grid carries no information.
Extjs
Ext.onReady(function(){
var store = new Ext.data.JsonStore({
// store configs
storeId: 'myStore',
proxy: {
type: 'ajax',
url: 'data.php',
reader: {
type: 'json',
root: 'country',
idProperty: 'total'
}
},
//alternatively, a Ext.data.Model name can be given (see Ext.data.Store for an example)
fields: ['name', 'area']
});
Ext.create('Ext.grid.Panel', {
title: 'Retorno',
//store: Ext.data.StoreManager.lookup('simpsonsStore'),
store:store,
columns: [
{ text: 'Name', dataIndex: 'name' },
{ text: 'Area', dataIndex: 'area', flex: 1 }
],
height: 200,
width: 400,
renderTo: Ext.getBody()
});
});
data.php here is the code with json code.
<?php
print '{
"total": 10,
"country": [
{
"name": "CULTIV",
"area": "6.96120082466223e-007"
},
{
"name": "asdASdasd",
"area": "123123123"
}
]
}';
?>
I think you need to set the store's autoLoad configuration to true. If you do not set this attribute, then you will need to call the load() method of the store.
Option 1
var store = new Ext.data.JsonStore({
// store configs
storeId: 'myStore',
autoLoad:true,
proxy: {
type: 'ajax',
url: 'data.php',
reader: {
type: 'json',
root: 'country'
//idProperty: 'total'
}
},
//alternatively, a Ext.data.Model name can be given (see Ext.data.Store for an example)
fields: ['name', 'area']
});
Option 2
var store = new Ext.data.JsonStore({
// store configs
storeId: 'myStore',
proxy: {
type: 'ajax',
url: 'data.php',
reader: {
type: 'json',
root: 'country'
//idProperty: 'total'
}
},
//alternatively, a Ext.data.Model name can be given (see Ext.data.Store for an example)
fields: ['name', 'area']
});
store.load();
I created a working fiddle for a demonstration.

Highstock - How to add multiple series with JSON-Array

My target: I want to draw HighStock-chart with multiple series. Data is loaded by AJAX from data.php. The output of data.php is an JSON-Array
My problem: I don't know hot to grab the data from JSON Array
The output is e.g
[[timestamp,value1,value2],[timestamp,value1,value2]]
Series 1 should be -> timestamp and value1
Series 2 should be -> timestamp and value2
This is my code
// Draw the chart
$(function(){
/* The chart is drawn by getting the specific data from "data.php".
* The configuration settings are transmitted by GET-Method. The output is an JSON-Array. */
$.getJSON('data.php',
function(data) {
chart = new Highcharts.StockChart
({
chart: { renderTo: 'chartcontainer', type: 'line' },
title: { text: 'You see the data of the last hour!' },
xAxis: { type: 'datetime', title: { text: 'time' } },
yAxis: { title: { text: 'unit' } },
series: [{ name: 'series1', data: data },{ name: 'series2', data: data }],
});
});
});
I think i have to change
series: [{ name: 'series1', data: data },{ name: 'series2', data: data }],
But I dont know in to what
Iterate through all items of the data array, and populate two separate arrays:
var series1 = [];
var series2 = [];
for (var i = 0; i < data.length; i++) {
series1.push([data[0], data[1]);
series1.push([data[0], data[2]);
}
You then have the timestamp-value pairs in each of the series arrays.
Doing this in php might be more efficient, especially if you can replace the current json creation.

Categories