I'm trying to convert the static data to using database results. I'll be using MySQL and PHP.
Example Code:
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
},
{
label: "My Second dataset",
fillColor : "rgba(151,187,205,0.2)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(151,187,205,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
Below is my php/msql:
$result = mysql_query("SELECT COUNT(*) FROM customer WHERE month='january'") or die(mysql_error());
$row1 = mysql_fetch_array( $result );
$result = mysql_query("SELECT COUNT(*) FROM customer WHERE month='february'") or die(mysql_error());
$row2 = mysql_fetch_array( $result );
$result = mysql_query("SELECT COUNT(*) FROM customer WHERE month='march'") or die(mysql_error());
$row3 = mysql_fetch_array( $result );
How could I use those count() from my MySQL query and implement it to datasets on chartjs? I would also like the labels to be generated from my MySQL query too. Should I loop the datasets inside the jQuery code?
This is the plugin that I'm using : http://www.chartjs.org/docs/#line-chart-introduction
First get your data into suitable data structures using PHP
$months = array("january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december");
$monthvalues = array();
foreach ($months as $month) {
$monthvalues[$month] = 0;
}
$result = mysql_query("SELECT month, count(*) FROM customer group by month") or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$monthvalues[$row[0]] = (int)$row[1];
}
Below that, just plug in those data structures into your Javascript
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : <?=json_encode($months);?>,
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : <?=json_encode(array_values($monthvalues));?>
}
]
}
assuming the the window.onload and the HTML for the canvas element are in their proper places.
Please place your php code into another file called api.php and use $.ajax to get these data with JSON format. To convert data into JSON format data you should use json_encode() php function.
I have set sample example you can see here.
Please refer below code example:
api.php
$arrLabels = array("January","February","March","April","May","June","July");
$arrDatasets = array('label' => "My First dataset",'fillColor' => "rgba(220,220,220,0.2)", 'strokeColor' => "rgba(220,220,220,1)", 'pointColor' => "rgba(220,220,220,1)", 'pointStrokeColor' => "#fff", 'pointHighlightFill' => "#fff", 'pointHighlightStroke' => "rgba(220,220,220,1)", 'data' => array('28', '48', '40', '19', '86', '27', '90'));
$arrReturn = array(array('labels' => $arrLabels, 'datasets' => $arrDatasets));
print (json_encode($arrReturn));
example.html
$.ajax({
type: 'POST',
url: 'api.php',
success: function (data) {
lineChartData = data;//alert(JSON.stringify(data));
var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Line(lineChartData);
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {responsive: true});
}
});
Please note that you should pass value of randomScalingFactor() at api.php.
Please check and let me know if you require any further help.
This is based on the answer above with a couple of changes.
php:
include 'db.php';
$query = "SELECT month, COUNT(*) count FROM customer WHERE month='march' GROUP BY month";
if ($stmt = $conn->prepare($query)) {
$stmt->execute();
$stmt->bind_result($month, $count);
$labels = array();
$data = array();
while ($stmt->fetch()) {
$labels[] = $month;
$data[] = $count;
}
$stmt->close();
}
$datasets = array('label'=>"timer",'data'=> $data);
$data = array('labels'=>$labels, 'datasets'=> array($datasets));
echo json_encode($data);
I had to use JSON.pare() on the passed-in array.
Javascript:
$.ajax({
type: 'POST',
url: 'api.php ',
datatype: 'json',
success: function (result) {
var ctx = document.getElementById("chart").getContext("2d");
var mychart = new Chart(ctx,
{
type: 'bar',
data: JSON.parse(result),
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
})
}
})
html:
<canvas id="chart" width="200" height="200"></canvas>
Related
new to this and (almost) desperate. in below code i want to set $rows1['date'][] = $data['tanggal']; data as X-Axis in highchart :
$(function () {
var chart;
$(document).ready(function() {
getAjaxData(1);
var val = location.search.split('proyek=')[1]
getAjaxData(val);
function getAjaxData(proyek){
$.getJSON("src/json/data.php", {proyek: proyek}, function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'scurve-proyek',
type: 'column'
},
title: {
text: ''
},
credits: {
enabled: false,
},
subtitle: {
text: ''
},
yAxis: {
min: 0,
max: 100,
tickInterval: 20,
title: {
text: ''
},
},
xAxis: {
type: 'datetime',
labels: {
formatter: function ( ){
return Highcharts.dateFormat('%Y-%m-%d', this.value);
},
},
},
tooltip:{
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.numberFormat(this.y, 2) +' %';
},
},
plotOptions: {
column: {
dataLabels: {
enabled: true,
format: '{point.y:,.2f}'+'%',
}
},
},
series: json
});
});
};
});
});
my data.php :
<?php
header("Content-type: application/json");
require_once "database.php";
$db = new database();
$mysqli = $db->connect();
$proyek = $_GET['proyek'];
$sql = "SELECT fren_pr FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows = array();
$rows['name'] = 'Rencana';
$rows['color'] = '#50B432';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows['data'][] = array($data['fren_pr'],);
}
$sql = "SELECT freal_pr, tanggal FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows1 = array();
$rows1['name'] = 'Realisasi';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows1['data'][] = $data['freal_pr'];
$rows1['date'][] = $data['tanggal'];
}
$rslt = array();
array_push($rslt, $rows);
array_push($rslt, $rows1);
print json_encode($rslt, JSON_NUMERIC_CHECK);
$mysqli->close();
this is my json view :
I've spent a lot of time trying to solve it but haven't found a solution until now.
Is there an error in my php code?
hope someone will be kind enough to help, Thanks in advance.
I am trying to add a dynamic select list to a Datatables Editor form. This is what I have tried:
var discipline_options = [];
$.getJSON('program_data/get_disciplines.php', function (data) {
$.each(data, function (index) {
discipline_options.push({
value: data[index].value,
label: data[index].text
});
});
editor.field( 'discipline_outcome.discipline_fk' ).update(discipline_options);
});
var editor = new $.fn.dataTable.Editor( {
ajax: "program_data/discipline_outcome_data.php",
table: "#discipline_outcome_table",
template: '#discipline_outcome_form',
fields: [ {
label: "Discipline:",
name: "discipline_outcome.discipline_fk",
type: "select",
placeholder: 'Choose discipline...',
placeholderDisabled: false,
placeholderValue: 0,
options: []
},...
The get_disciplines.php script is:
$data = array();
$query = "SELECT * FROM discipline";
$result = $connection->query( $query );
while ($row = mysqli_fetch_array($result)) {
$data[] = array("label"=>$row['discipline'], "value"=>$row['discipline_pk']);
}
$temp = array('disciplines[].discipline_pk'=>$data);
$json = array('options'=>$temp);
echo json_encode($json);
This script returns the following JSON, but the select list is still empty:
{
"options": {
"disciplines[].discipline_pk": [
{
"label": "Emergency Medicine",
"value": "1"
},
{
"label": "General Practice",
"value": "2"
},
{
"label": "Internal Medicine",
"value": "3"
}
]
}
}
I got it working using:
var discipline_options = [];
$.getJSON("program_data/get_disciplines.php", function(data) {
var option = {};
$.each(data, function(i,e) {
option.label = e.text;
option.value = e.id;
discipline_options.push(option);
option = {};
});
}
).done(function() {
editor.field('discipline.discipline_pk').update(discipline_options);
});
var editor = new $.fn.dataTable.Editor( {
ajax: "program_data/discipline_outcome_data.php",
table: "#discipline_outcome_table",
template: '#discipline_outcome_form',
fields: [ {
label: "Discipline:",
name: "discipline.discipline_pk",
type: "select",
placeholder: 'Choose discipline...',
placeholderDisabled: false,
placeholderValue: 0,
options: []
},...
and the get_disciplines.php:
$data = array();
$query = "SELECT * FROM discipline";
$result = $connection->query( $query );
while ($row = mysqli_fetch_array($result)) {
$data[] = array("text"=>$row['discipline'], "id"=>$row['discipline_pk']);
}
echo json_encode($data);
I want to show on the chart the number of new students registered and the number of online students per month. I got the data but I don't know how to transfer data into js file to draw that chart.
Here is js file.
var chart = document.getElementById('products-sales');
let newStudent = $("#monthNewStudent").val();
let onlStudent = $("#monthOnline").val();
var newStudentArr = newStudent.split(",");
var onlStudentArr = onlStudent.split(",");
let arrNew = JSON.parse(newStudentArr);
let arrOnl = JSON.parse(onlStudentArr);
arrData = [];
for (var i in arrNew) {
arrData.push({
month:i,
newStudent: arrNew[i],
onlStudent: arrOnl[i]
});
}
var months = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
Morris.Area({
element: 'products-sales',
data: [{
month: '2017-01',
newstudent: 0,
online: 0,
}],
xkey: 'month',
ykeys: ['newstudent', 'online'],
labels: ['Học viên mới', 'Học viên online'],
xLabelFormat: function(x) { // <--- x.getMonth() returns valid index
var month = months[x.getMonth()];
return month;
},
dateFormat: function(x) {
var month = months[new Date(x).getMonth()];
return month;
},
behaveLikeLine: true,
ymax: 300,
resize: true,
pointSize: 0,
pointStrokeColors:['#00B5B8', '#FA8E57', '#F25E75'],
smooth: true,
gridLineColor: '#E4E7ED',
numLines: 6,
gridtextSize: 14,
lineWidth: 0,
fillOpacity: 0.9,
hideHover: 'auto',
lineColors: ['#00B5B8', '#FA8E57', '#F25E75'],
data:arrData
});
My controller to count the number of new students registered and the number of online students per month
class DashboardController extends AdminBaseController
{
public function index ()
{
$month = 1;
$studNew = [];
$studOnline = [];
$studActive = [];
for($i = $month; $i < 13; $i++) {
//count new students
$newStudents = Member::where('member_type_id',1)->whereMonth('created_at', $i)->get();
$studNew[$i] = $newStudents->count();
//students online
$onlStudents = Member::where('member_type_id',1)->whereMonth('updated_at', $i)->get();
$studOnline[$i] = $onlStudents->count();
// count card active
$act = Order::where('status', "active")->whereMonth('updated_at', $i)->get();
$studActive[$i] = $act->count();
}
$monthNewStudent = json_encode($studNew);
$monthOnline = json_encode($studOnline);
$monthActive = json_encode($studActive);
return view('admin.dashboard.index', compact('monthNewStudent',
'monthOnline',
'monthActive'));
}
}
You can set values in a variable and then can pass that variable to view. At view, you can use that variable like below:
{!! $yourvariable !!}
So in your case, it will be like this:
data: {!! $yourvariable !!},
Hope it helps you!!
I am new to datatables and I am making a website search data using datatables. But mysql data is more than 10,000. When I try to search data on my web, datatables are very long displaying data. Can anyone help me, how do I get datatables to display tables faster with large data. Thank you
PHP:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "test");
$columns = array('id', 'datetime', 'temperature', 'humidity');
$query = "SELECT id, datetime, temperature, humidity FROM data WHERE ";
if($_POST["is_date_search"] == "yes")
{
$query .= 'DATE(datetime) BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["search"]["value"]))
{
$query .= '
(id LIKE "%'.$_POST["search"]["value"].'%")
';
}
if(isset($_POST["order"]))
{
$query .= "GROUP BY DATE_FORMAT(datetime, '%d-%M-%Y-%H:%i:%s') ORDER BY 'id'";
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query );
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = "";
$sub_array[] = $row["datetime"];
$sub_array[] = $row["temperature"];
$sub_array[] = $row["humidity"];
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM data";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
Javascript:
$(document).ready(function(){
$('.input-daterange').datepicker({
todayBtn:'linked',
format: "yyyy-mm-dd",
autoclose: true
});
fetch_data('no');
function fetch_data(is_date_search, start_date='', end_date='')
{
var dataTable = $('#tabel_data').DataTable({
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]],
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
filename: 'datatable'
},
],
"paging": false,
"processing" : true,
"serverSide" : true,
bFilter:false,
"ajax" : {
url:"fetch.php",
type:"POST",
data:{
is_date_search:is_date_search, start_date:start_date, end_date:end_date
},
}
});
dataTable.on('draw.dt', function () {
var info = dataTable.page.info();
dataTable.column(0, { search: 'applied', order: 'applied', page: 'applied', }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + info.start;
dataTable.cell(cell).invalidate('dom');
});
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date !='')
{
$('#tabel_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
document.getElementById('tabel').style.display = "block";
}
else
{
alert("Date Required");
}
});
});
1) use pagination how to use pagination with PHP and mysql instead of a simple query like below.
"SELECT * FROM data";
2) Dot select * because * will select unnecessary fields also instead define column name for which you want to show data
example:
select name,page,amt from data
your final query will look like
SELECT emp_id, emp_name, emp_salary FROM employee LIMIT $offset, $rec_limit;
check the link above how to use pagination with PHP and mysql
Hi guys i need help with Highcharts library, i have this array coming from php,
[{"name":"25% en cambio de aceite 76 lubricants","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3]]},{"name":"10% Descuento en filtro de aceite","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3],["2015-10-03",3],["2015-10-05",1],["2015-10-09",1],["2015-10-10",1]]}]
I need to show this as line chart dynamically, but have been unable to do it, i believe the error comes from the quotes in dates, needs to be in format [Date.UTC(2015, 2, 6), 3]
This is my php function that returns the json data
public function actionTransactionsRedeemed() {
// Transacciones Totales redimidas por merchant
$sql = "SELECT DISTINCT `transaction`.idPromotion, promotion.`name` FROM `transaction` INNER JOIN promotion ON `transaction`.idPromotion = promotion.idPromotion WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion IS NOT NULL";
$idPromotion = Yii::app()->db->createCommand($sql)->queryAll();
$idPromotions = array();
$tempArray = array();
$result = array();
$i = 1;
$rs = array();
foreach($idPromotion as $i){
//process each item here
$id = $i["idPromotion"];
$tempArray['name'] = $i["name"];
$sql = "SELECT count(*) AS count, DATE(`transaction`.date) AS `date` FROM `transaction` WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion = $id GROUP BY DATE(`transaction`.date)";
$transactionsRedeemed = Yii::app()->db->createCommand($sql)->queryAll();
foreach($transactionsRedeemed as $item2){
$rs[0] = $item2['date'];
$rs[1] = $item2['count'];
$tempArray['data'][] = $rs;
$rs = array();
}
$i++;
array_push($result, $tempArray);
}
//$result = json_encode($result, JSON_NUMERIC_CHECK);
//echo json_decode($result);
print json_encode($result, JSON_NUMERIC_CHECK);
}
And this is the Jquery that builds the chart
$(document).ready(function() {
var options = {
chart: {
type: 'spline',
renderTo: 'chart-merchant-day',
defaultSeriesType: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Total de promociones redimidas',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%l%p', this.value);
}
}
},
yAxis: {
title: {
text: 'Transacciones'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%l%p', this.x-(24000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Count'
}],
credits: false
}
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var lines = [];
traffic = [];
var data = $.parseJSON(tsv);
var x = 0;
//console.log(tsv);
$.each(data, function(i, item) {
//alert(item);
//console.log(item);
$.each(item, function(y, item2) {
if(y == "data"){
//console.log(item2);
try {
tsv = item2;
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
options.series[x].data.push([Date.parse(line[0]),line[1]]);
/*date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);*/
});
} catch (e) { }
options.series[x].data = traffic;
} else if(y == "name"){
options.series[x].name = item2;
}
});
x++;
});
chart = new Highcharts.Chart(options);
//console.log(tsv.replace(/\"/g, ""));
//tsv = tsv.replace(/\"/g, "");
});
});
Any help will be greatly appreciated, im so exhausted at this point.
The function is actually simpler,
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var data = $.parseJSON(tsv);
$.each(data, function (i, item) {
options.series.push({
name: item['name'],
data: []
});
$.each(item['data'], function (j, dataitem) {
var dataitemvalue = null;
try {
dataitemvalue = [Date.parse(dataitem[0]), dataitem[1]];
} catch (e) {}
options.series[i].data.push(dataitemvalue);
});
});
chart = new Highcharts.Chart(options);
});
JSFiddle demo