ChartJS and Ajax calls - php

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
}
});
}

Related

how to combine to array for chartjs width 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.

Why do I get undefined after looping an array of objects in jquery?

I want to create a bar chart using chartjs,PHP and MySql. After querying the database to get product details as a json object, now I want to iterate over the array and add product_name and price into new arrays, of which I get undefined. What might be wrong to my code?
$(document).ready(function(){
$.ajax({
url: "../controller/products-chart-data.php",
method: "GET",
success: function(data){
console.log(data);
var product = [];
var price = [];
for (var i in data) {
product.push(data[i].product_name);
price.push(data[i].price);
}
var chartData = {
labels: product,
datasets: [
{
label: "Product Price",
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: price
}
]
};
var context = $("#products-chart");
var barGraph = new Chart(context, {
type: 'bar',
data: chartData
});
},
error: function(data){
console.log(data);
}
})
})
PHP code for the database query:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'shopping_cart_with_paypal');
$getAllproductsQuery = $conn->query("SELECT * FROM tbl_products");
$data = array();
foreach ($getAllproductsQuery as $row) {
$data[] = $row;
}
$getAllproductsQuery->close();
$conn->close();
print json_encode($data);
Sample data:
[{"id":"3","product_name":"Travel
bag","price":"5000","category_id":"1","product_image":"travel-
bag.jpeg","average_rating_id":"3","description":"Lather travel bag, found in
different sizes","product_code":"203"},{"id":"4","product_name":"Jewel
Box","price":"6000","category_id":"4","product_image":"jewel-
box.jpeg","average_rating_id":"5","description":"Modern jewel box straight
dubai","product_code":"204"},{"id":"5","product_name":"Wooden
Dolls","price":"9000","category_id":"5","product_image":"wooden-
dolls.jpeg","average_rating_id":"3","description":"wooden dolls made of pure
woods","product_code":"205"}]

ChartJS not showing from MySQL

PHP: chart_db.php
<?php
require_once ('dbh.inc.php');
$JSON_Response = array();
//Counts the number of Active
$count_active = mysqli_query($db, "SELECT client_id FROM client WHERE status = 1");
$JSON_Response['active'] = mysqli_num_rows($count_active);
//Counts the number of Inactive
$count_inactive = mysqli_query($db, "SELECT client_id FROM client WHERE status = 0");
$JSON_Response['inactive'] = mysqli_num_rows($count_inactive);
error_log('hello');
echo json_encode($JSON_Response);
?>
JS: chart.js
$(document).ready(function(){
$.ajax({
url:"http://localhost/FAME/private/includes/chart_db.php",
method: "GET",
success: function(response){
var data = JSON.parse(response);
var activeData = text(data.active);
var inactiveData = text(data.inactive);
console.log(activeData);
var ctx = document.getElementById('piechart').getContext('2d');
var statusChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Active', 'Inactive'],
datasets: [{
pointStyle: 'circle',
backgroundColor: [ 'rgb(78, 115, 223)', 'rgb(25, 179, 211)' ],
data: activeData, inactiveData
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
segmentShowStroke: false,
cutoutPercentage: 70,
legend: {
onClick: false,
position: 'bottom',
labels: {
usePointStyle: true
}
}
}
});
}
});
});
Question: The problem is that in the data in chart are not showing. The entire chart is not showing. And with the log from chrome inspection: it says that there is an error: "Uncaught ReferenceError: text is not defined".
This has nothing to do with php, mysql or xampp. You are using an undefined method called text. The error message says it all. Check your third and fourth lines in the ajax success. You have:
var activeData = text(data.active);
Replace it with :
var activeData = data.active;
and see what happens.

jVectormap adding markers from database only adds one marker

I am trying to add markers from a MySQL database via PHP into jvectormap (version 2.0.2).
I'm not sure what I'm doing wrong but when I add the markers dynamically using .AddMarkers, only a single marker shows up, which is the last marker in the JSON response.
This is my code:
JavaScript:
$("#airportsmap").vectorMap({
map: "world_mill_en",
scaleColors: ["#eff0f1", "#eff0f1"],
normalizeFunction: "polynomial",
hoverOpacity: .7,
hoverColor: !1,
regionStyle: {
initial: {
fill: "#6673a7"
}
},
markerStyle: {
initial: {
stroke: "transparent"
},
hover: {
stroke: "rgba(112, 112, 112, 0.30)"
}
},
backgroundColor: "transparent",
markers:[]
});
function loadairportmarkers(){
$.ajax({
type: "POST",
url: "modules/getfavouriteairportsdash.php",
dataType: 'json',
cache: false,
success: function(response) {
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
addMapPoint(value[3], value[4], value[2]);
});
} else {
$.each(response.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
}
})
}
function addMapPoint(lat, lon, title){
var map = $('#airportsmap').vectorMap('get', 'mapObject');
map.addMarkers([{ latLng: [lat, lon], name: title }], []);
}
PHP
$stmt = $mysqli->prepare("
SELECT .... query here
");
$stmt->bind_param('is', $uid,$emp);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_all())
{
$returnResult = $row;
}
}
mysqli_close($mysqli);
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
This results in the following JSON response:
{"result":[["HUEN","FAOR","Entebbe International Airport","0.042386","32.443501"],["GABS","FAOR","Modibo Keita International Airport","12.5335","-7.94994"]],"errors":false}

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
}]
});
});

Categories