how to foreach datasets in chartjs laravel - 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

Related

creating pie graph with laravel with json response

i want to know how to get laravel javascript query for my chart
why does it always return the data without making a pie chart, always to the json view
code in view:
<script>
// get data from database using Ajax or fetch
fetch('/api/data')
.then(response => {
let data = response.data;
let ctx = document.getElementById('myChart').getContext('2d');
let myChart = new Chart(ctx, {
type: 'pie',
data: data
});
})
.catch(error => {
console.log(error);
});
code in controller:
$data = DB::table('suara')
->groupBy('suara')
->pluck(DB::raw('sum(jml_suara) as sum'), 'suara')
->toarray();
// format data for pie chart
$labels = [];
$values = [];
foreach ($data as $item => $key) {
$labels[] = $item;
$values[] = $key;
}return response()->json([
'labels' => $labels,
'datasets' => [
[
'data' => $values,
'backgroundColor' => ['#FF6384', '#36A2EB', '#FFCE56', '#F44336']
]
]
]);

get first value from array column database

I need to get the fist item an array from select database using loop for but when i do't my outfit display all the value for array
public function index() {
$hall=DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','imagas.image_path')
->get();
$results =[];
foreach ($hall as $halls ) {
$array=$halls->image_path ;
for ($i=0; $i<$array; $i++) {
$halls=$array[0];
}
array_push($results, $halls);
}
return response()->json($results);
}
JSON Output
[
{ "id": 159,
"hall_name": "asdad",
"image_path": "[\"1579635948.jpg\",\"1579635948.jpg\",\"1579635948.png\",\"1579635948.png\"]"
},
{
"id": 160,
"hall_name": "dsfdsf",
"image_path": "[\"1579636069.jpg\",\"1579636069.png\",\"1579636069.png\",\"1579636069.png\"]"
},
]
I want to display the first value from all image_pathlike this
[ {
"id": 160,
"hall_name": "dsfdsf",
"image_path": "["1579636069.jpg"]"
},
]
You may use decode your $hall->image_path string before loop through it
public function index() {
$halls = DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','imagas.image_path')
->get();
$results =[];
foreach ($halls as $hall) {
$array = json_decode($hall->image_path, true);
if (is_array($array)) {
$hall->image_path = reset($array) ?? NULL;
array_push($results, $hall);
}
}
return response()->json($results);
}
If I understand you correctly, you want the whole collection data but with modified image_path column, so it contains only the first path, right?
Here is the code using map helper function to output the collection as you desire:
public function index() {
$hall=DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','imagas.image_path')
->get();
$results = $hall->map(function ($item, $key) {
is_array($item->image_path) ? [head($item->image_path)] : [$item->image_path];
return $item;
});
return response()->json($results);
// [ { "id": 159, "hall_name": "asdad", "image_path": "["1579635948.jpg"]" },
// { "id": 160, "hall_name": "dsfdsf", "image_path": "["1579636069.png"]" }]
}

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;

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