Dynamic Chart Using Google API In Codeigniter 3.0 - codeigniter

I Am using Google API to show the graph depending on my result of month and mount so, I have taken below code to display the graph here i have static values but i want to give dynamic values
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, options);
}
</script>
And this is my controller
public function overviews()
{
$data['monthlyTotals'] = $this->livemerchant_model->overviews();
if ($this->input->post('transactionMerchant,transactionYear')) {
$data['monthlyTotals'] = $this->livemerchant_model->overviews($this->input->post('transactionMerchant'), $this->input->post('transactionYear'));
} else {
$data['monthlyTotals'] = $this->livemerchant_model->overviews();
}
$this->load->view('overviews', $data);
}
This is My Model
function overviews($theYear='',$theMonth='')
{
$this->db->select("DATEPART(Year, TRANS_TransactionDate) [TheYear], DATEPART(Month, TRANS_TransactionDate) [TheMonth], DATENAME(Month, TRANS_TransactionDate) [TheMonthName], SUM(TRANS_Amount) [TotalAmount]", false);
$this->db->from('BTBL_Transactions');
if ($theYear != '') {
$this->db->where("DATEPART(Year, TRANS_TransactionDate) = '" . $theYear . "'", NULL, FALSE);
}
if ($theMonth != '') {
$this->db->where("DATEPART(Month, TRANS_TransactionDate) = '" . $theMonth . "'", NULL, FALSE);
}
$this->db->group_by("DATEPART(Year, TRANS_TransactionDate), DATEPART(Month, TRANS_TransactionDate), DATENAME(Month, TRANS_TransactionDate)");
$this->db->order_by("1", "asc");
$this->db->order_by("2", "asc");
$this->db->order_by("3", "asc");
$query = $this->db->get();
//echo $this->db->last_query();die();
return $query->result();
}

Related

how to foreach datasets in chartjs laravel

I have a problem that I can't loop datasets chartjs in laravel.
below is my code in model
public function umur($tanggal)
{
return DB::table('riwayat')
->select('umur')
->where('tanggal_riwayat', $tanggal)
->groupBy('umur')
->get();
}
public function data_grafik($tanggal, $umur)
{
return DB::table('riwayat')
->select('hasil_keputusan', DB::raw('COUNT(id_riwayat) as jml_riwayat'))
->where('tanggal_riwayat', $tanggal)
->where('umur', $umur)
->groupBy('hasil_keputusan')
->get();
}
this is my controller
$tanggal="2022-08-10";
$query = $this->m_dashboard->grafik($tanggal);
$dataa = [];
foreach ($query as $row) {
$dataa['label'][] = $row->umur;
$data_grafik=$this->m_dashboard->data_grafik($tanggal, $row->umur);
foreach ($data_grafik as $value) {
$dataa['label_1'][] = $value->hasil_keputusan;
$dataa['jml_riwayat'][] = $value->jml_riwayat;
}
}
$data = [
'chart_data' => json_encode($dataa),
];
return view('admin.dashboard', $data);
this is my view
var cData = JSON.parse('<?php echo $chart_data; ?>');
const labels = cData.label;
const data = {
labels: labels,
datasets: [{
label: cData.label_1,
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: cData.jml_riwayat,
}
]
};
const config = {
type: 'bar',
data: data,
options: {}
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
this is my output
and this is the ouput what I want
Thanks in advance and sorry for occasional english mistakes

How to retrieve dates for beforeShowDay in Jquery-ui datepicker

I am needing to disable some dates in jquery-ui
The following code works perfectly:
var unavailableDates =["19-6-2020","21-6-2020","29-6-2020"];
var dateToday = new Date();
var dateToday=
$(function() {
$( "#date_picker" ).datepicker({
dateFormat: 'dd-mm-yy',
minDate: dateToday,
onSelect: function(dateText) {
alert("Selected date: " + dateText);
},
beforeShowDay:unavailable
});
});
function unavailable(date) {
//alert ("Function"+unavailableDates);
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
However I am needing to retrieve the unavailable dates from a mysql database. this is the ajax return:
["19-6-2020","21-6-2020","29-6-2020"]
The string is created by php thus:
$temp="[";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$ date=date("j-n-Y", strtotime($row["date_unavailable"]));
$ temp=$temp.'"'.$date.'",';
}//end while
$temp = rtrim($temp, ",");
$temp=$temp."]";
echo $temp;
exit();
When I try to use this returned string none of the unavailable dates show. The string is actually detected by the unavailable function but it is ignoring it (no errors displayed)
There is obviously a problem with the returned string but I cant see what it is.
Any pointers to the problem much appreciated
Consider the following JavaScript:
$(function() {
function getUnDates() {
var results;
$.getJSON("getDates.php", function(data) {
results = data;
});
return results;
}
function unavailable(date) {
var dmy = $.datepicker.formatDate("dd-mm-yy", date);
var result = [false, "", "Unavailable"];
if ($.inArray(dmy, unavailableDates) == -1) {
result = [true, ""];
}
return result;
}
var unavailableDates = getUnDates();
var dateToday = new Date();
$("#date_picker").datepicker({
dateFormat: 'dd-mm-yy',
minDate: dateToday,
onSelect: function(dateText) {
alert("Selected date: " + dateText);
},
beforeShowDay: unavailable
});
});
Then use this in a Stand Alone PHP Script:
$results = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$date = date("j-n-Y", strtotime($row["date_unavailable"]));
array_push($result, $date);
}
header('Content-Type: application/json');
echo json_encode($result);
exit();

Laravel - How to use my Query to represent 1 as Male and 2 as Female in Chart

In my Larave-5.8, I am trying to generate bar chart using:
public function report()
{
$userCompany = Auth::user()->company_id;
$userId = Auth::user()->id;
$gender_datas = HrEmployee::selectRaw('count(gender_id) as count,gender_id')->where('company_id', $userCompany)->groupBy('gender_id')->get();
$data=array();
foreach ($gender_datas as $result) {
$data[$result->gender_id]=(int)$result->count;
}
return view('report-default')
->with('data', $data);
}
View
<div id="piechart_3d" style="width: 650px; height: 450px;"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var record={!! json_encode($data) !!};
console.log(record);
// Create our data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'Total_Signup');
for(var k in record){
var v = record[k];
data.addRow([k,v]);
console.log(v);
}
var options = {
title: 'Gender Classification',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
</script>
From the table table, gender_id is an integer field. 1=Male and 2=Female.
In my Chart it is displaying 1 and 2.
I want it to display 1 as male and 2 as female.
How do I use my Query to represent 1 as Male and 2 as Female
How do I achieve this?
Thank you
Off the cuff option:
You could use a case statement in the selectRaw query.
selectRaw("count(gender_id) as count,CASE WHEN gender_id = 1 THEN 'Male' WHEN
gender_id = 2 THEN 'Female' ELSE 'Unknown' END as gender")
This solution assumes that only 1 or 2 value exist for gender.
$userCompany = Auth::user()->company_id;
return HrEmployee::where('company_id', $userCompany)
->groupBy('gender_id')
->get([DB::raw('IF(gender_id = "1", "MALE", "FEMALE") as gender, count(gender_id) as total')])
->pluck('total', 'gender');
{
"MALE": 13,
"FEMALE": 7
}

Doing live search in codeigniter via ajax , mongodb

This is my ajax code which fetches all data from data and display in the table, but when I input an alphabet in search-box, it again fetches complete data inside the table
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "<?php echo base_url() ?>Appconfig/get_masteradmin_data?query="+query,true);
xhttp.onload= function()
{
if (xhttp.status >=200 && xhttp.status <400)
{
var data= JSON.parse(xhttp.responseText);
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<tr>'+
'<td>'+data[i].full_name+'</td>'+
'<td>'+data[i].username+'</td>'+
'<td>'+data[i].designation+'</td>'+
'<td>'+data[i].department+'</td>'+
'<td>'+data[i].official_mobile_no+'</td>'+
'<td>'+data[i].official_email_id+'</td>'+
'<td>'+data[i].select_user_type+'</td>'+
'<td>'+data[i].permission+'</td>'+
'</tr>';
}
showdata.insertAdjacentHTML('beforeend',html);
}
else
{
console.log("Try again after some time");
}
};
xhttp.send();
}
$('#search').keyup(function(){
var search = $(this).val();
//console.log(search);
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
This is my model for fetching data from my mongodb collection.
public function get_masteradmin_data($query)
{
$mongo = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$query= '';
//$filter = ['full_name' => 'www'];
$regex = new MongoDB\BSON\Regex ($query);
$filter = ['full_name'=>$regex,];
$options =[
'projection' => [
'_id' => 0,
'full_name' => 1,
'username' => 1,
'designation'=> 1,
'department'=> 1,
'official_mobile_no'=> 1,
'official_email_id'=> 1,
'select_user_type'=> 1,
'permission'=> 1,
],
'sort' => [
'_id' => -1
],
];
$query = new MongoDB\Driver\Query($filter, $options);
//$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$result = $mongo->executeQuery('justrack_db.master_admin', $query);
$res = array();
foreach($result as $r)
{
$res[] = $r;
}
return json_encode($res,true);
//return $res;
}
This is my controller for displaying data. I am not sure, but I think there is some issue in my controller, as I tried to echo $query but it shows nothing. I am not able to understand how to fix this.
public function get_masteradmin_data()
{
$query = '';
$this->load->model('AppconfigModel');
$this->master_admin();
if($this->input->post('query'))
{
$query = $this->input->post('query');
}
$result= $this->AppconfigModel->get_masteradmin_data($query);
echo ($result);
}

Passing SQL data in codeigniter to highcharts with JSON

I am having trouble passing SQL data from my controller to my view. I have verified the information shows up from my model. I don't know JSON very well but I'm trying to learn. My goal is to populate a chart with two fields that are just numbers into this highcharts javascript. Please help, thank you!
Controller
function dashboard() {
// Tickets in Queue
$query = $this->mhedash_model->maint_pending_tickets();
$result3 = $query->result_array();
$this->table->set_heading('Work Number', 'Vehicle Number','Submit Date','Submit Time');
$data['table']['Vehicle in Queue'] = $this->table->generate_table($result3);
// Active Tickets
$query = $this->mhedash_model->select_active();
$result = $query->result_array();
$this->table->set_heading('Service Number','Start Date','Mechanic','Vehicle Number','Description','Type');
$data['table']['Vehicles Actively Being Worked On'] = $this->table->generate_table($result);
// Tickets Waiting On Parts
$query = $this->mhedash_model->select_pending_parts();
$result2 = $query->result_array();
$this->table->set_heading('Service Number','Start Date','Mechanic','Vehicle Number','Description','Type');
$data['table']['Waiting For Parts'] = $this->table->generate_table($result2);
//Graph - Availble Highreaches
$query = $this->mhedash_model->graph_available_hr();
$result4 = $query->result_array();
$data['row'][''] = $this->table->generate_table($result4);
$query = $this->mhedash_model->graph_available_dt();
$result5 = $query->result_array();
$data['row'][''] = $this->table->generate_table($result5);
$series_data[] = array('name' => 'available', 'data' => (int)$result4);
$series_data[] = array('name' => 'not_available', 'data' => (int)$result5);
$this->view_data['series_data'] = json_encode($series_data, JSON_NUMERIC_CHECK);
// Load view
$data['page_title'] = 'MHE Dashboard';
$data['main_content'] = 'mhe/mhe_dashboard_view';
$data['array'] = $result;
$data['array2'] = $result2;
$data['array3'] = $result3;
print json_encode($series_data);
//echo json_encode($series_data, JSON_NUMERIC_CHECK);
return $this->load->view('includes/template',$data);
}
View that has the highcharts javascript
var chart;
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
xAxis: {
categories: ['one', 'two']
},
plotOptions: {
series: {
allowPointSelect: true
}
},
series: [{
data: [<?php echo join($series_data, ',') ?>]
}]
});
// the button action
$('#button').click(function () {
var chart = $('#container').highcharts(),
selectedPoints = chart.getSelectedPoints();
if (chart.lbl) {
chart.lbl.destroy();
}
chart.lbl = chart.renderer.label('You selected ' + selectedPoints.length + ' points', 100, 60)
.attr({
padding: 10,
r: 5,
fill: Highcharts.getOptions().colors[1],
zIndex: 5
})
.css({
color: 'white'
})
.add();
});
});
</script>
Also, this is what prints when I print son_encode for my $series_data
[{"name":"available","data":1},{"name":"not_available","data":1}]

Resources