update yiiwheels highchart via javascript - javascript

I'm using highchart widget from yiiwheels (extension for Yii framework):
<?php $this->widget('yiiwheels.widgets.highcharts.WhHighCharts',array(
'pluginOptions' => array(
'title' => array('text' => 'Fruit Consumption'),
'xAxis' => array('categories' => array('Apples', 'Bananas', 'Oranges')),
'yAxis' => array('title' => array('text' => 'Fruit eaten')),
'series' => array(
array('name' => 'Jane', 'data' => array(1, 0, 4)),
array('name' => 'John', 'data' => array(5, 7, 3))
)
)
));?>
echo TbHtml::button('Refresh Chart', array('id'=>'refreshButton')); ?>
<script type="text/javascript">
$('#refreshButton').click(function() {
var chart = $('#container').highcharts(); // THIS IS NOT WORKING, HELP!!!
chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5] ); // sample data
});
</script>
This works well if I use native highcharts.js from highcharts.com
But like I said, I use yiiwheels's highcharts widget.
How can I fix this, how to refer my chart from javascript/jquery?
Thanks

Related

Yii2 How to pass php array data into highcharts

I am using Yii2 extension miloschuman/yii2-highcharts for charts and get confused passing php array into hightcharts.
My Array Values
Array
(
[Power Electronics] => 14.00
[Introduction to Programming] => 3.92
[Data base Management System] => 3.28
[Object Oriented Analysis and Design] => 1.96
)
Now simply what I want to add this data to my highcharts I am passing above array like my below code.
FROM MY HIGHCHARTS CODE
'series' => [
[
"name" => "Exam Results",
"data" => $course_data,
'dataLabels' => [
'enabled' => true,
'rotation' => -90,
'color' => '#FFFFFF',
'align' => 'right',
'format' => '{point.y:.1f}', // one decimal
'y' => 10, // 10 pixels down from the top
'style' => [],
'fontSize' => '13px',
'fontFamily' => 'Verdana, sans-serif',
],
],
],
I have already try many things but not get any success I wanted output like this charts.
Have you tried to call json_encode function with mentioned array passed as an argument? Here is the code:
<?php
$data = [
['Power Electronics', 14.00],
['Introduction to Programming', 3.92],
['Data base Management System', 3.28],
['Object Oriented Analysis and Design', 1.96],
];
echo json_encode($data);
[EDIT]
You can also try to use SeriesDataHelper feature. There is information about using it in the documentation, here is the link: https://github.com/miloschuman/yii2-highcharts/blob/master/doc/examples/series-data-helper.md#using-numerically-indexed-data
Here is example code:
use miloschuman\highcharts\SeriesDataHelper;
$data = $data = [
['Power Electronics', 14.00],
['Introduction to Programming', 3.92],
['Data base Management System', 3.28],
['Object Oriented Analysis and Design', 1.96],
]
'series' => [
[
"name" => "Exam Results",
"data" => new SeriesDataHelper($course_data, ['0:name', '1:y']),
'dataLabels' => [
'enabled' => true,
'rotation' => -90,
'color' => '#FFFFFF',
'align' => 'right',
'format' => '{point.y:.1f}', // one decimal
'y' => 10, // 10 pixels down from the top
'style' => [],
'fontSize' => '13px',
'fontFamily' => 'Verdana, sans-serif',
],
],
],
According to docs your array has invalid format. It should look like his:
$data = [
['Power Electronics', 14.00],
['Introduction to Programming', 3.92],
['Data base Management System', 3.28],
['Object Oriented Analysis and Design', 1.96],
];
You can fix this with simple foreach:
$newData = [];
foreach ($data as $key => $value) {
$newData[] = [$key, $value];
}

Datatables Date and Time Input

I'm trying to use the date and time input in datatables used here https://editor.datatables.net/examples/dates/datetime.html
This is what I've tried
<script type="text/javascript" src="<?php echo base_url('assets/js/jquery-3.1.1.min.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/materialize.min.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/jquery.dataTables.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/moment.js');?>"></script>
<script type="text/javascript">
//use a global for the submit and return data rendering in the examples
var editor;
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
table: '#receivablesLogs',
fields: [ {
label: 'Date:',
name: 'date'
type: 'datetime',
def: function () { return new Date(); },
format: 'MM-DD-YYYY',
fieldInfo: 'US style m-d-y date input'
},
{
label: 'Invoice Number:',
name: 'invoice_number'
},
{
label: 'Customer Name:',
name:'customer_name'
},
{
label: 'Total Amount:',
name: 'total_amount'
},
{
label: 'Due Date:',
name: 'due_date'
type: 'datetime',
def: function () { return new Date(); },
format: 'MM-DD-YYYY',
fieldInfo: 'US style m-d-y date input'
}
]
} );
$('#receivablesLogs').DataTable( {
dom: 'Bfrtip',
columns: [
{data: 'date'},
{data: 'invoice_number'},
{data: 'customer_name'},
{data: 'total_amount'},
{data: 'due_date'}
],
select: true,
order: [[ 0, 'asc' ]],
bFilter: false,
bLengthChange: false,
paging: false,
bFiler: false
});
});
</script>
and here is my table
<table id="receivables" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Date</th>
<th>Invoice Number</th>
<th>Customer Name</th>
<th>Total Amount</th>
<th>Due Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>03/31/2014</td>
<td>12456</td>
<td>Customer One</td>
<td>160,000.00</td>
<td>04/25/2015</td>
</tr>
<tr>
<td>02/28/2015</td>
<td>12456</td>
<td>Customer One</td>
<td>160,000.00</td>
<td>04/25/2015</td>
</tr>
</tbody>
</table>
But I don't know where I went wrong. I imported the correct js files but it doesn't display correctly. This is the output that I'm getting
Also I don't get what this line ajax: '../php/datetime.php' is for. I don't see what is the datetime.php that the documentation is referring to.
This is my first time trying datatables so I don't know where I did wrong. I already tried the basic creation of datatables and it worked but I had a problem when I tried to incorporate the date and time input in my codes.
UPDATE 1: There exists a server side script like this in the documentation
<?php
/*
* Example PHP implementation used for date time examples
*/
// DataTables PHP library
include( "../../php/DataTables.php" );
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Options,
DataTables\Editor\Upload,
DataTables\Editor\Validate;
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'users' )
->fields(
Field::inst( 'first_name' ),
Field::inst( 'last_name' ),
Field::inst( 'updated_date' )
->validator( 'Validate::dateFormat', array(
'empty' => false,
'format' => 'm-d-Y g:i A'
) )
->getFormatter( 'Format::datetime', array(
'from' => 'Y-m-d H:i:s',
'to' => 'm-d-Y g:i A'
) )
->setFormatter( 'Format::datetime', array(
'from' => 'm-d-Y g:i A',
'to' => 'Y-m-d H:i:s'
) ),
Field::inst( 'registered_date' )
->validator( 'Validate::dateFormat', array(
'format' => 'j M Y H:i'
) )
->getFormatter( 'Format::datetime', array(
'from' => 'Y-m-d H:i:s',
'to' => 'j M Y H:i'
) )
->setFormatter( 'Format::datetime', array(
'from' => 'j M Y H:i',
'to' => 'Y-m-d H:i:s'
) )
)
->process( $_POST )
->json();
Where should I put this?
I pull this code snippet from the site you provided a link for:
$('#example').DataTable( {
dom: 'Bfrtip',
ajax: '../php/datetime.php',
columns: [
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'updated_date' },
{ data: 'registered_date' }
],
select: true,
buttons: [
{ extend: 'create', editor: editor },
{ extend: 'edit', editor: editor },
{ extend: 'remove', editor: editor }
]
} );
Ajax is a set of techniques to load data dynamically, behind the scenes.
Some information here: https://developer.mozilla.org/en-US/docs/AJAX
The link: "../php/datetime.php" is given as an example.
datetime.php is a file you would have to actually make in php.
In this case, datetime.php runs on the back-end, and probably queries some database.

how to sum column in datatables (i'm using codeigniter)

I'm using codeigniter and datatables for my view data. But i'm stuck how to get sum column. I have 2 fields named barang_qty, and barang_qty_toko. I need to sum this and display on datatables.
This is my Controller :
function ajax_tableBarang(){
if(!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}else{
$this->load->library('datatables_ssp');
$table = 'barang';
$primaryKey = 'barang_id';
$columns = array(
array( 'db' => 'barang_id', 'dt' => 'DT_RowID' ),
array( 'db' => 'barang_kode', 'dt' => 'barang_kode' ),
array( 'db' => 'barang_type', 'dt' => 'barang_type' ),
array( 'db' => 'barang_size', 'dt' => 'barang_size' ),
array( 'db' => 'barang_qty', 'dt' => 'barang_qty'), //I want this field result from summation of barang_qty and barang_qty_toko
array( 'db' => 'barang_harga', 'dt' => 'barang_harga' ),
array( 'db' => 'barang_klasifikasi', 'dt' => 'barang_klasifikasi'),
);
$sql_details = array(
'user' => 'user',
'pass' => 'passwd',
'db' => 'pjtomato',
'host' => 'localhost'
);
$where = "";
echo json_encode(Datatables_ssp::simple($_GET, $sql_details, $table, $primaryKey, $columns, $where));
}
}
And this is my view :
<div role="tabpanel" class="tab-pane fade in active" id="tab-all">
<table id="tableAllItem" class="table table-bordered table-striped table-hover" cellspacing="0" width="100%">
<thead>
<tr class="info">
<th>#</th>
<th>Kode</th>
<th>Jenis</th>
<th>Ukuran</th>
<th>Quantity</th> // Total of quantity (summation of barang_qty + barang_qty_toko) will display here
<th>Harga</th>
<th>Klasifikasi</th>
</tr>
</thead>
</table>
And this is the javascript for datatables:
<script type="text/javascript">
$.fn.dataTableExt.oApi.fnPagingInfo = function (oSettings){
return{
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength),
"iTotalPages": Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength)
};
};
var t = $('#tableAllItem').DataTable({
"processing": true,
"serverSide": true,
"ajax": "<?php echo site_url('cAdminPage/ajax_tableBarang'); ?>",
"columns": [
{ "data": "barang_kode" },
{ "data": "barang_kode" },
{ "data": "barang_type" },
{ "data": "barang_size" },
{ "data": "barang_qty"},
{ "data": "barang_harga" },
{ "data": "barang_klasifikasi" },
],
"order": [[1, 'asc']],
"rowCallback": function (row, data, iDisplayIndex){
var info = this.fnPagingInfo();
var page = info.iPage;
var length = info.iLength;
var index = page * length + (iDisplayIndex + 1);
$('td:eq(0)', row).html(index);
}
});
Please advice,
Thanks

Highcharts json php multiple series

I have a simple question but for some reason can't find the solution. As described here: highcharts documentation, I made the following script:
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
},
title: {
text: 'Dagelijks waterverbruik'
},
subtitle: {
text: 'Waterverbruik in liters'
},
xAxis: {
categories: [
'Zondag',
'Maanag',
'Dinsdag',
'Woensdag',
'Donderdag',
'Vrijdag',
'Zaterdag'
]
},
yAxis: {
min: 0,
title: {
text: 'Waterverbruik (Liter)'
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{}]
};
$.getJSON('testdata.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
my testdata.php is as follows:
<?php
header('Content-Type: application/json');
$data[] = array('Zondag',11);
$data[] = array('Maandag',10);
$data[] = array('Dinsdag',9);
$data[] = array('Woensdag',8);
$data[] = array('Donderdag',12);
$data[] = array('Vrijdag',2);
$data[] = array('Zaterdag',18);
$serie1[] = array('name' => 'serie 1', 'data' => $data);
$serie1[] = array('name' => 'serie 2', 'data' => $data);
echo json_encode($serie1);
?>
For some reason the charts don't render. What am I doing wrong? One series is working this way, but multiple series don't.
As you can see I would expect two bars with the same value. The output of testdata.php is:
[{"name":"serie 1","data":[["Zondag",11],["Maandag",10],["Dinsdag",9],["Woensdag",8],["Donderdag",12],["Vrijdag",2],["Zaterdag",18]]},{"name":"serie 2","data":[["Zondag",11],["Maandag",10],["Dinsdag",9],["Woensdag",8],["Donderdag",12],["Vrijdag",2],["Zaterdag",18]]}]
You make the array like this and do not use categories in the $data array because you are using static categories in chart.following is a hint
$data = array(11,10,9,8,12,81);
$serie1[] = array('name' => 'serie 1', 'data' => $data);
$serie1[] = array('name' => 'serie 2', 'data' => $data);
echo json_encode($serie1);
In this part:
$.getJSON('testdata.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
Change it to this
$.getJSON('testdata.php', function(data) {
options.series = data;
var chart = new Highcharts.Chart(options);
});
You current code can only accomodate one series since you specified an index to the series i.e. [0].
In the JSON you need to set JSON_NUMERIC_CHECK flag, because in your example it seems that you have no numebr values on data.

How to show MySQL data in graph?

I want to retrieve data from mysql in the form of graph with the following code. But, nothing is shown. Can anybody help me?
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "graphdata.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales','width':500,'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
<?php
echo("<div id='chart_div'></div>");
?>
Here is my getdata.php:
$sql = "SELECT count(`booth_number`),`sold_by` FROM `registration1` where week(`Date`) = week(curdate()) GROUP BY `sold_by`";
$result = mysql_query($sql, $conn) or die(mysql_error());
//start the json data in the format Google Chart js/API expects to recieve it
$data = array(
'cols' => array(
array('label' => 'Month', 'type' => 'string'),
array('label' => 'Ticket Sales', 'type' => 'string')
),
'rows' => array()
);
while($row = mysql_fetch_row($result)) {
$data['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}
echo json_encode($data);
As mentioned, I think you need to move your code inside the success callback:
function drawChart() {
$.ajax({
url: "graphdata.php",
type: "GET",
dataType:"json",
success: function(jsonData, textStatus, jqXHR) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales','width':500,'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
});
}
[edit] A working example (with some mocked data) can be found on jsBin.
[edit2] Update the example on jsBin with the output provided in the duplicate question:
{
"cols": [
{
"label":"Month",
"type":"string"
},{
"label":"Weekly Sales",
"type":"string"
}
],
"rows": [
{
"c":[
{"v":"3"},
{"v":"jaspreet singh "}
]
},{
"c":[
{"v":"3"},
{"v":"joseph swanson"}
]
}
]
}
The JSON returned by the server is wrong, the object should look like this:
"cols": [
{
"label":"Month",
"type":"string"
},{
"label":"Weekly Sales",
"type":"number"
}
],
"rows": [
{
"c":[
{"v":"jaspreet singh "},
{"v":"3"}
]
},{
"c":[
{"v":"joseph swanson"},
{"v":"3"}
]
}
]
};
The changes needed should now be obvious. Hope this helps.
[edit3] getdata.php should contain the following snippet imho:
$data = array(
'cols' => array(
array('label' => 'Month', 'type' => 'string'),
array('label' => 'Ticket Sales', 'type' => 'number')
),
'rows' => array()
);
while($row = mysql_fetch_row($result)) {
$data['rows'][] = array(
'c' => array(
array('v' => $row[1]),
array('v' => $row[0])
)
);
}

Categories