Highcharts Data filtering can't populate MySQL PHP - codeigniter

I created a highchart to show issued items in a store for my Codeigniter project. Controller as follows :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Chart extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('data');
}
public function index()
{
$this->load->view('charts/chart');
}
public function data()
{
$data = $this->data->get_request_data();
$branch= $this->data->getBranch();
$category = array();
$category['name'] = 'Item';
$series3 = array();
$series3['name'] = 'Issued Qty';
foreach ($data as $row)
{
$category['data'][] = $row->item;
$series3['data'][] = $row->issued_qty;
}
$result = array();
array_push($result,$category);
array_push($result,$series3);
print json_encode($result, JSON_NUMERIC_CHECK);
}
}
Model
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Data extends CI_Model {
function __construct()
{
parent::__construct();
}
function getBranch()
{
$q = $this->db->get_where('store_branch', array('status' => '1'));
if ($q->num_rows() > 0) {
return $q->result();
}
return FALSE;
}
function get_request_data()
{
$branch = $this->session->userdata('branch_id');
$this->db->select('sur.update_stock_id, sus.branch_id, sus.request_no, sus.billed_date, store_branch.branch_name,
si.item_id, si.item_name AS item, tf.avqty, sur.r_qty as r_qty, sur.ap_qty as ap_qty,
tf1.issued_qty');
$this->db->from('store_update_request sur');
$this->db->join('store_update_stock sus', 'sus.update_stock_id=sur.update_stock_id', 'left');
$this->db->join('store_branch', 'sus.branch_id=store_branch.branch_id', 'left');
$this->db->join('store_item si', 'sur.item=si.item_id', 'left');
$this->db->join('(select update_stock_id, item, is_qty AS issued_qty
from store_update_issue
where store_update_issue.status=1
) AS tf1',
'si.item_id=tf1.item AND sur.update_stock_id = tf1.update_stock_id','left' );
$this->db->join('(select item, sum(qty) AS avqty
from store_update_stock_details
where store_update_stock_details.status=1
group by item) AS tf', 'si.item_id=tf.item', 'left');
$this->db->where(array('sus.status' => '1'));
$this->db->group_by('si.item_id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
}
return false;
}
}
View
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$('#branch').change(function() {
var id = $('#branch').val();
getAjaxData(id);
});
var options = {
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
rangeSelector: {
selected: 1,
inputDateFormat: '%Y-%m-%d'
},
title: {
text: 'Item Issued Summary',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: ['']
},
yAxis: [{
title: {
text: 'No of Issues'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
],
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
plotOptions: {
column: {
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
y: 10, // 10 pixels down from the top
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}
},
series: []
}
$.getJSON("data", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
function getAjaxData(id) {
$.getJSON("data.php", {id: id}, function(json) {
options.xAxis.categories = json[0]['data']; //xAxis: {categories: []}
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
}
// ]]></script>
<?php
if (!empty($branch)) {
$common = $branch[0];
}
?>
<body>
<input type="button" class="btn btn-warning" value="Back to Home"><br></br>
<div class="col-md-3">
<div class="form-group"><label>Branch / Section</label>
<select name="branch" id="branch" class="form-control select2" >
<option value="">Select Branch / Section</option>
<?php
if (!empty($common)) {
foreach ($common as $row) {
?>
<option value="<?= $row->branch_id ?>"><?= $row->branch_name ?></option>
<?php
}
}
?>
</select>
</div>
</div>
<script type='text/javascript' src='<?php echo base_url(); ?>assets/js/highcharts.js'></script>
<script type='text/javascript' src='<?php echo base_url(); ?>assets/js/exporting.js'></script>
<div id="container" style="min-width: 400px; height: 500px; margin: 0 auto;"></div>
The code has generated expecting result / chart as follows :
But the branch wise data filterring in the chart is not working. Even drop down list is not populating.
What may be going wrong ? Can anyone help me ?

Related

How to pass data from controller to view using AJAX

I want to show a data controller to view using ajax and I have already shown a data controller to view on the chart bar without ajax I need to get data on the chart bar using ajax but I don't have an idea how to show data on chart bar using ajax.
I don't have that good experience in JSON/AJAX/Laravel, I'm a beginner.
Controller
public function index()
{
$manager_hourlog = Hourlog::with('project', "user")->get()-
>groupBy('project.name');
$projects = [];
$totals = [];
foreach ($manager_hourlog as $key => $val) {
$projects[] = $key;
}
foreach ($manager_hourlog as $key2 => $val) {
$minutes = $val->sum('hour_work');
$totals[] = round($minutes / 60, 1);
}
$users = User::where("status", 1)->get();
$data = [
// manager report
'manager_projects' => $projects,
'totals' => $totals,
"manager_hourlog" => $manager_hourlog,
"auth" => $auth,
];
return response()->json(['data' => $data]);
return view('cms.dashboard', $data);
}
Script
<script>
// Employee report script
var colors = ["#1abc9c", "#2ecc71", "#3498db",
"#9b59b6", "#34495e", "#16a085", "#27ae60"];
#if ($auth->user_type != 1)
// manager report script
var managerchartbar = {
labels: {!! json_encode($manager_projects) !!},
datasets: [
#foreach($users as $user)
{
label: {!! json_encode($user->name) !!},
backgroundColor: colors[Math.floor(Math.random() * colors.length)],
// data: [300,200,500,700]
data: [
#foreach($manager_hourlog as $hourlog)
{{$hourlog->where("user_id", $user->id)->sum("hour_work") / 60}},
#endforeach
]
},
#endforeach
]
};
var ctx = document.getElementById('manager').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: managerchartbar,
options: {
title: {
display: true,
text: 'Employees Report chart'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
#endif
ajax
$.ajax({
type: 'GET',
url: '{{url("/dashboard")}}',
data: {
data: data
},
success: function(data){
console.log(data.data);
},
error: function(xhr){
console.log(xhr.responseText);
}
});
</script>
Html VIew
<div class="col-md-12">
<div class="card-box">
<div class="container-fluid">
<canvas id="manager" height="100">
</canvas>
</div>
</br>
</div>
</div>
Route
Route::get('/dashboard',
'DashboardController#index')->name('dashboard');

i have an error when use chart on laravel

Can someone can help me? I get an error when I try to use a chart.
Undefined variable: label (View: C:\xampp\htdocs\latihan_penjualan\resources\views\home.blade.php)
in 15bd1eeee4b4d1b903b52322d785ce7ce1ab31d2.php line 31
This is my controller:
public function index()
{
$kategori = DB::table('kategoris')->get();
$data = [];
$label = [];
foreach ($kategori as $i => $v) {
$value[$i] = DB::table('produks')->where('id_kategori',$v->id)->count();
$label[$i] = $v->nama;
}
return view('home');
$this->with('value',json_encode($value));
$this->with('label',json_encode($label));
}
And this is my view:
<div id="container" style="width: 100%;">
<canvas id="canvas"></canvas>
</div>
<script type="text/javascript" src="http://www.chartjs.org/dist/2.7.2/Chart.bundle.js"></script>
<script type="text/javascript" src="http://www.chartjs.org/samples/latest/utils.js"></script>
<script type="text/javascript">
var color = Chart.helpers.color;
var barChartData = {labels: {!! $label !!},
datasets: [{
label: 'Produk Per Kategori',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
borderWidth: 1,
data: {!! $value !!},
}],
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Grafik Data Produk'
}
}
});
};
</script>
I already declared the variable $label.
Thanks in advance.
return view('home')
->with(['value'=>json_encode($value),'label'=>json_encode($label)]);
Fix this part after return view('home');
public function index()
{
$kategori = DB::table('kategoris')->get();
$data = [];
$label = [];
foreach ($kategori as $i => $v) {
$value[$i] = DB::table('produks')->where('id_kategori',$v->id)->count();
$label[$i] = $v->nama;
}
return view('home')->with('value',json_encode($value))->with('label',json_encode($label));
}

Cropped image encrypted data not post in codeigniter on live server. Why?

I have a situation where a user select photo and cropped it.After cropping encoded data passed to hidden input has successfully but when posting my form the image data not post.Only blank page shown.
Same code are working fine on local server. But on live server this happened to me.
Let me share my code. Please guide me where i am doing wrong.
$(".gambar").attr("src", "<?php echo base_url().'assets/img/users/defualt.jpg");
var $uploadCrop,
tempFilename,
rawImg,
imageId;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.upload-demo').addClass('ready');
$('#cropImagePop').modal('show');
rawImg = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 150,
height: 150,
type: 'circle'
},
boundary: {
width: 265,
height: 265
},
enforceBoundary: false,
enableExif: true,
enableOrientation: true,
orientation: 4,
});
$('#cropImagePop').on('shown.bs.modal', function(){
$uploadCrop.croppie('bind', {
url: rawImg
}).then(function(){
});
});
$('.item-img').on('change', function () {
imageId = $(this).data('id');
tempFilename = $(this).val();
$('#cancelCropBtn').data('id', imageId);
readFile(this); });
$('#cropImageBtn').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
format: 'jpeg',
size: {width: 150, height: 150}
}).then(function (resp) {
$('#imageEncoder').val(resp);
$('#item-img-output').attr('src', resp);
$('#cropImagePop').modal('hide');
$('#profile_form').submit();
});
});
<form action="<?= base_url().'userController/update_staff_picture' ?>" method="post" enctype="multipart/form-data" id="profile_form">
<input type="hidden" name="imageEncoder" id="imageEncoder">
<label class="cabinet center-block">
<figure>
<img src="" class="gambar img-responsive img-thumbnail img-circle" id="item-img-output" />
<figcaption><i class="fa fa-camera"></i></figcaption>
</figure>
<input type="file" class="item-img file center-block" name="file_photo"/>
</label>
</form>
User Controller
public function update_staff_picture(){
$data = $this->input->post('imageEncoder');
echo "<pre>";
print_r($data);
exit();
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$image_name = date('ymdgis').'.png';
$req['image']=$image_name;
file_put_contents('./assets/img/users/'.$image_name, $data);
$this->db->set($req);
$this->db->where('userID',$userID);
$this->db->update('users');
redirect(base_url().'staff-profile/'.$_POST['userID']);
}

how can I change pdf from datatable for pdf for serverside html2pdf?

I want to change my button pdf from buttons datatable for my pdf from server, but in the same position how can I do it? my url from html2pdf http://localhost/store_websocket/inventory/pdf and I want to change the button from pdfmaker from datatable in the position for my url for html2pdf because I want researching datatables fails with 1k or more rows then I decide server side procesing
controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class PDF extends MY_Controller {
public function __construct(){
parent::__construct();
}
public function index(){
require_once(APPPATH.'third_party/html2pdf/vendor/autoload.php');
$data['products'] = $this->products->datatable();
//print_r($data);
$template_pdf = $this->load->view('view_pdf', $data, TRUE);
$html2pdf = new HTML2PDF('P', 'A4', 'en');
$html2pdf->WriteHTML($template_pdf);
$html2pdf->Output('exemple.pdf');
}
}
view
<style type="text/css">
P {text-align:justify;font-size: 12pt;}
li {text-align:justify;font-size: 12pt;}
table.page_footer {width: 100%; border: none; border-top: solid 1px #000000; }
table.products {border-collapse: collapse; width: 100%;}
table.products th,td {text-align: left; padding: 8px;}
table.products thead tr{font-size: 9.5pt}
table.products th {background-color: #34495e; color: white;}
tbody tr {background-color: #f2f2f2;}
</style>
<page backtop="14mm" backbottom="14mm" backleft="10mm" backright="10mm" style="font-size: 12pt">
<page_footer>
<table class="page_footer">
<tr>
<td style="width: 100%; text-align: right">
page [[page_cu]]/[[page_nb]]
</td>
</tr>
</table>
</page_footer>
<div style="width:100%;text-align:center;">
<h1><b>List Inventory</b></h1>
</div>
<table class="products">
<thead>
<tr>
<th>Codigo</th>
<th>Descripcion</th>
<th>Precio compra</th>
<th>Precio venta</th>
<th>Precio mayoreo</th>
<th>Existencia</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $key): ?>
<tr>
<td><?php echo $key['id']?></td>
<td><?php echo $key['descripcion']?></td>
<td><?php echo $key['precio_compra']?></td>
<td><?php echo $key['precio_venta']?></td>
<td><?php echo $key['precio_mayoreo']?></td>
<td><?php echo $key['existencia']?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</page>
AJAX
$(function(){
URL_GET_DATATABLE = BASE_URL+'inventory/product/datatable';
URL_GET_VIEW_PRODUCT = BASE_URL+'inventory/product/getViewProduct';
URL_GET_ADD_PRODUCT = BASE_URL+'inventory/product/addProduct';
var table = $('#example').DataTable({
"lengthChange": false,
responsive: true,
dom: 'Blfrtip',
buttons: [{
extend: 'excelHtml5',
exportOptions:{
columns: [1,2,3,4,5,6]
}
},{
extend: 'csvHtml5',
exportOptions:{
columns: [1,2,3,4,5,6]
}
},{
extend: 'pdf',
exportOptions: {
columns: [1,2,3,4,5,6]
}
}],
ajax: {
url: URL_GET_DATATABLE,
type: 'POST',
},
columnDefs:[{
targets: -1,
data: null,
defaultContent: "<a href='#'><span class='glyphicon glyphicon-pencil'></span></a>"
},{
targets: 6,
render: function (data) {
return (data == 1) ? "<span class='label label-success'>active</span>":"<span class='label label-danger'>inactive</span>";
}
}],
fnRowCallback: function (data,nRow) {
if (nRow[6] == 0) {
$(data).css({'background-color':'#f2dede'})
}else if(nRow[6] == 1){
$(data).css({'background-color':'#dff0d8'})
}else{
}
}
});
$('#example tbody').on('click','a', function(e){
alert('thing');
});
$('#add').on('click',function(){
$("#description").mask("(999) 999-9999");
$("#new_product").validate();
BootstrapDialog.show({
type: BootstrapDialog.TYPE_PRIMARY,
message: function(dialog) {
var $message = $('<div></div>');
var pageToLoad = dialog.getData('pageToLoad');
$message.load(pageToLoad);
return $message;
},
data: {
'pageToLoad': URL_GET_VIEW_PRODUCT
},
closable: false,
buttons:[{
id: 'btn-ok',
cssClass: 'btn-primary',
icon: 'glyphicon glyphicon-send',
label: ' Save',
action: function (e) {
var description = $('#description').val();
var cost_price = $('#cost_price').val();
var selling_price = $('#selling_price').val();
var wprice = $('#wprice').val();
var min_stock = $('#min_stock').val();
var stock = $('#stock').val();
var max_stock = $('#max_stock').val();
if($("#new_product").valid()){
$.ajax({
url: URL_GET_ADD_PRODUCT,
type: 'POST',
data: {description: description, cost_price: cost_price, selling_price: selling_price, wprice: wprice, min_stock: min_stock, stock: stock, max_stock: max_stock}
}).done(function (data) {
console.log(data);
if (data.msg == 'successfully added') {
$('#new_product')[0].reset();
table.ajax.reload();
}else if(data.min_stock == 'el stock no puede ser mayor al min'){
BootstrapDialog.show({
type: BootstrapDialog.TYPE_WARNING,
message: 'el stock no puede ser mayor al min'
});
}
});
return false;
}
}
},{
id: 'btn-cancel',
cssClass: 'btn-danger',
icon: 'glyphicon glyphicon-remove',
label: ' Cancel',
action: function (e) {
e.close();
}
}]
});
});
});

Generate Highchart using from date range MYSQL Ajax

I am trying to generate a bar graph using data from MYSQL through ajax by taking two input date fields from the user and returning the results using ajax.The problem is that when i select the date range, it doesn't show me anything.
I am new to Ajax as well, so any help will be appreciated.
Below is the code i have tried so far;
Thanks
<?php
$cakeDescription = "Highcharts Pie Chart";
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><?php echo $cakeDescription ?></title>
<link href="../webroot/css/cake.generic.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//default
var startdate = document.getElementById('startdate').value;
var enddate = document.getElementById('enddate').value;
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Highcharts Chart PHP with MySQL Example',
x: -20 //center
},
subtitle: {
text: 'Sumber : Jabatan XYZ',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Jumlah Pelawat'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>:<b>{point.y}</b> of total<br/>'
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y}'
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -40,
y: 100,
floating: true,
borderWidth: 1,
shadow: true
},
series: []
};
function getAjaxData(startdate,enddate) {
$.getJSON("data.php", function(json) {
options.xAxis.categories = json[0]['data']; //xAxis: {categories: []}
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
}
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<a class="link_header" href="/highcharts/"><< Back to index</a>
<div class="menu_top" >
<input type="date" id="startdate" name="startddate">
<input type="date" id="enddate" name="enddate">
</div>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto;"></div>
</body>
</html>
Below is my data.phpfile,
<?php
#Basic Line
require '../../conn/connection.php';
$id = $_GET['id'];
$startdate = $_GET['startdate'];
$enddate = $_GET['enddate'];
$result = mysql_query("SELECT DISTINCT(membername), COUNT(membername)
AS member
FROM responses WHERE timerecorded>=" . $startdate . " AND timerecorded<=" . $enddate . " GROUP BY membername");
$bln = array();
$bln['name'] = 'Bulan';
$rows['name'] = 'Jumlah Pelawat';
while ($r = mysql_fetch_array($result)) {
$bln['data'][] = $r['membername'];
$rows['data'][] = $r['member'];
}
$rslt = array();
array_push($rslt, $bln);
array_push($rslt, $rows);
print json_encode($rslt, JSON_NUMERIC_CHECK);
mysql_close($con);

Resources