Passing SQL data in codeigniter to highcharts with JSON - codeigniter

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

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

Laravel 7: Full Calendar not showing events

Please see my code first:
Controller:
public function getHolidays($days, $start_date) {
$date = date('Y-m-d',strtotime($start_date));
$i = 0;
$response = array();
while ($i <= 42) {
$tsDate = strtotime($date. ' ' .'+ '.$i.' days');
$day = date('D', $tsDate);
if(in_array($day, $days)) {
$data = array();
$data['title'] = 'Weekend';
$data['start'] = date('Y-m-d',$tsDate);
$data['end'] = date('Y-m-d',$tsDate);
$response[] = $data;
}
$i++;
}
return $response;
}
public function index(request $request){
if($request->ajax()) {
$weekends = DB::table('working_days')
->where('status', 0)
->get(['day'])
->map(function($item) {
return $item->day;
})->toArray();
$holidays = DB::table('holidays')
->get()
->map(function($item) {
return [
'title' => 'Holiday',
'start' => Carbon::parse($item->date)->format('Y-m-d'),
'end' => Carbon::parse($item->date)->format('Y-m-d'),
];
})->toArray();
$attendances = DB::table('attendances as a')
// ->where('leave_cat_id', '!=', null)
->where('user_id', Auth::user()->id)
->get()
->map(function($item) {
return [
'title' => 'Leave',
'start' => Carbon::parse($item->date)->format('Y-m-d'),
'end' => Carbon::parse($item->date)->format('Y-m-d'),
'color' => 'red',
];
})->toArray();
$data = [...$this->getHolidays($weekends, $request->start), ...$holidays, ...$attendances];
return response()->json($data);
}
return view('admin.dashboard');
}
Blade File script:
<script>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var calendar = $('#full-calendar').fullCalendar({
editable: true,
editable: true,
events: '/dashboard',
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
});
});
</script>
Tables:
attendances
id
user_id
date
status
leave_cat_id
1
2
2022-07-13
1
null
2
2
2022-07-12
0
1
holidays
id
date
1
2022-07-13
2
2022-07-20
working_days
id
day
working_status
1
Fri
0
2
Sat
1
3
Sun
1
I want to show attendances on Full Calendar [https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.js]
First, weekly holiday will show when the working_status = 0 and day is matched with calendar.
Second, holidays will show when it will match the dates with calendar date
Third, attendance will show on other days. If the status is 1 it will show present and if 0 it will show absent. Also, if the leave_cat_id column is not equal to null, then it will show On leave, others it will show the attendance status.
Can you please modify my code for this?
Thanks
public function getHolidays($days, $start_date) {
$date = date('Y-m-d',strtotime($start_date));
$i = 0;
$response = array();
while ($i <= 42) {
$tsDate = strtotime($date. ' ' .'+ '.$i.' days');
$day = date('D', $tsDate);
if(in_array($day, $days)) {
$data = array();
$data['title'] = 'Weekend';
$data['start'] = date('Y-m-d',$tsDate);
$data['end'] = date('Y-m-d',$tsDate);
$response[] = $data;
}
$i++;
}
return $response;
}
public function index(request $request){
if($request->ajax()) {
$weekends = DB::table('working_days')
->where('working_status''status', 0)
->get(['day'])
->map(function($item) {
return $item->day;
})->toArray();
$holiday$holidays = DB::table('holidays')
->get()
->map(function($item) {
return [
'title' => 'Holiday',
'start' => Carbon::parse($item->date)->format('Y-m-d'),
'end' => Carbon::parse($item->date)->format('Y-m-d'),
];
})->toArray();
$attendances = DB::table('attendances''attendances as a')
// ->where('leave_cat_id', '!=', null)
->where('user_id', Auth::user()->id)
->get()
->map(function($item) {
return [
'title' => $item->leave_cat_id ? 'Leave' : ($item->attendance_status == 1 ? 'Present' : 'Absent'),
'start' => Carbon::parse($item->attendance_date>date)->format('Y-m-d'),
'end' => Carbon::parse($item->attendance_date>date)->format('Y-m-d'),
'color' => $item->attendance_status == 1 ? 'green' : 'red',
];
})->toArray();
$data = [...$this->getHolidays($weekends, $request->start), ...$holiday$holidays, ...$attendances];
return response()->json($data);
}
return view('admin.dashboard');
}
<script type="text/javascript"><script>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var calendar = $('#full-calendar').fullCalendar({
editable: true,
editable: true,
events: '/dashboard',
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
});
});
</script>

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

How to Ajax with select2 auto fill another input field

please your help ,how to auto fill with ajax + select2 using medoo framework database to autofill another input in same form .
this my ajax code :
$('.matrix').select2({
ajax: {
url: "index.php",
dataType: 'json',
data: function (params,page) {
return {
q: params.term, // search term
qa: 'matrix'
};
},
processResults: function (data,params) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
},
//cache: true,
},
minimumInputLength: 3,
placeholder: "<?php _e('Please Select'); ?>",
});
Please your advice .
This my search data :
case "matrix":
$searchstring = "";
if(isset($_GET['q'])) $searchstring = $_GET['q'];
if($searchstring != "") {
$items = $database->select("tbl_matrix", "*", [ "OR" => [
"bc_name[~]" => $searchstring
]]);
} else {
$items = $database->select("tbl_matrix", "*");
}
$results = array();
$results[0]['id'] = 0;
$results[0]['text'] = __('None');
$i = 1;
foreach($items as $item) {
$results[$i]['id'] = $item['id'];
$results[$i]['text'] = $item['bc_code']." ".$item['bc_name'];
$i++;
}
echo json_encode($results);
break;

Dynamic Chart Using Google API In Codeigniter 3.0

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

Resources