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));
}
Related
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 ?
I want to filter the data in my table. I have seen many tutorials online but do not understand. I found a tutorial that seemed very complicated to me. I just want to use a controller and view. Constants are used in that tutorial and the filter data is static but I don't want to use it and my filter data is dynamic. Help me out as a newbie.
The code of the tutorial is given here
app/Constants/GlobalConstants
<?php
namespace App\Constants;
class GlobalConstants {
const USER_TYPE_FRONTEND = "frontend";
const USER_TYPE_BACKEND = "backend";
const ALL = 'All';
const LIST_TYPE = [self::USER_TYPE_FRONTEND, self::USER_TYPE_BACKEND];
const LIST_COUNTRIES = ["Canada", "Uganda", "Malaysia", "Finland", "Spain", "Norway"];
const SALARY_RANGE = ['401762', '85295', '287072', '456969', '354165'];
}
App/User
public static function getUsers($search_keyword, $country, $sort_by, $range) {
$users = DB::table('users');
if($search_keyword && !empty($search_keyword)) {
$users->where(function($q) use ($search_keyword) {
$q->where('users.fname', 'like', "%{$search_keyword}%")
->orWhere('users.lname', 'like', "%{$search_keyword}%");
});
}
// Filter By Country
if($country && $country!= GlobalConstants::ALL) {
$users = $users->where('users.country', $country);
}
// Filter By Type
if($sort_by) {
$sort_by = lcfirst($sort_by);
if($sort_by == GlobalConstants::USER_TYPE_FRONTEND) {
$users = $users->where('users.type', $sort_by);
} else if($sort_by == GlobalConstants::USER_TYPE_BACKEND) {
$users = $users->where('users.type', $sort_by);
}
}
// Filter By Salaries
if ($range && $range != GlobalConstants::ALL) {
$users = $users->where('users.salary', $range);
}
return $users->paginate(PER_PAGE_LIMIT);
}
App/Http/Controllers/HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Constants\GlobalConstants;
class HomeController extends Controller
{
public function index() {
$users = User::getUsers('', GlobalConstants::ALL, GlobalConstants::ALL, GlobalConstants::ALL);
return view('home')->with('users', $users);
}
public function getMoreUsers(Request $request) {
$query = $request->search_query;
$country = $request->country;
$sort_by = $request->sort_by;
$range = $request->range;
if($request->ajax()) {
$users = User::getUsers($query, $country, $sort_by, $range);
return view('pages.user_data', compact('users'))->render();
}
}
}
view code
#foreach($users as $key)
<div class="card">
<div class="card-header">
<img src="{{ asset('assets/images/dev.png') }}" alt="" />
</div>
<div class="card-body">
<span class="tag tag-pink">{{ $key->type }}</span>
<hr>
<span class="tag tag-salary">Salary: {{ $key->salary }}</span>
<h4>{{ $key->email }}</h4>
<p>
{{ $key->address }}
</p>
<h4>Country: {{ $key->country }}</h4>
<div class="user">
#php
$user=App\User::find($key->id)
#endphp
<img src="{{ asset('assets/images/user-3.jpg') }}" alt="" />
<div class="key-info">
<h5>{{ $user['fullname'] }}</h5>
<small>{{ date('d.m.Y H:i:s', strtotime($key->created_at)) }}</small>
</div>
</div>
</div>
</div>
#endforeach
<script>
$(document).ready(function() {
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
getMoreUsers(page);
});
$('#search').on('keyup', function() {
$value = $(this).val();
getMoreUsers(1);
});
$('#country').on('change', function() {
getMoreUsers();
});
$('#sort_by').on('change', function (e) {
getMoreUsers();
});
$('#salary_range').on('change', function (e) {
getMoreUsers();
});
});
function getMoreUsers(page) {
var search = $('#search').val();
// Search on based of country
var selectedCountry = $("#country option:selected").val();
// Search on based of type
var selectedType = $("#sort_by option:selected").val();
// Search on based of salary
var selectedRange = $("#salary_range option:selected").val();
$.ajax({
type: "GET",
data: {
'search_query':search,
'country': selectedCountry,
'sort_by': selectedType,
'range': selectedRange
},
url: "{{ route('users.get-more-users') }}" + "?page=" + page,
success:function(data) {
$('#user_data').html(data);
}
});
}
</script>
public function create(Request $request)
{
$doctors = Doctors::all();
$query = doctors_slots::query();
'services.','consultation.')
// ->get();
if($request->ajax()){
$doctors_slots = $query->where(['doc_id'=>$request->doctors])->get();
return response()->json(compact('doctors_slot'));
}
$doctors_slots = $query->get();
return view('Admin.booking.add_booking',compact('doctors','doctors_slots'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#doctors").on('change', function() {
var doctors = $(this).val();
$.ajax({
url: "{{ route('booking') }}",
type: "GET",
data: {
'doctors': doctors
},
success: function(data) {
var doctors_slots = data.doctors_slots;
var html = '';
if (doctors_slots.length > 0) {
for (let i = 0; i < doctors_slots.length; i++) {
html += '<option value="' + doctors_slots[i][
'available_time_start'
] + '' + doctors_slots[i]['available_time_end'] + '">\
' + doctors_slots[i]['available_time_start'] + ' To\
' + doctors_slots[i]['available_time_end'] + '\
</option>';
}
} else {
html += '<option>No Data Found</option>';
}
$('#option').html(html);
}
});
});
});
</script>
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 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']);
}
I want a pie chart of expenses in percentage,my code is below, when i run the code it is not displaying nothing.please help.if possible please correct the code. i am really confused,only blank page is coming.
my controller chart
class Chart extends CI_Controller {
function chart() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('chart_m');
$this->load->library('session');
}
public function index()
{
$data['pie'] = json_encode($this->chart_m->selectexpenses());
$this->load->view('home',$data);
}
}
model chart_m
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Chart_m extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function selectexpenses()
{
$results = $this->db->query("SELECT expenses from myTable");
return $results->result_array();
}
}
my view page home.php
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<head><script>
$(document).ready(function () {
$(function () {
var chart;
// Build the chart
$('.widget-lower-left#widget').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'expenses'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'expenses',
data: []
}]
});
});
function requestData() {
$.ajax({
url:'<?php echo base_url().'index.php/chart'?>',
datatype: "json",
success: function(data) {
alert(data);
console.log(data);
var newData = [];
for( var i = 0, len = data.length; i < len; i++ ) {
var item = data[i];
for(var j in item){
newData.push([j,item[j]]);
}
}
chart.series[0].setData(newData);
</script>
},
cache: false
});
};
});
////////////////////////
May be You should Try This..
RewriteEngine on
RewriteCond $1 !^(index\.php|public|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
The controller is like
<?php
class Charts extends Controller {
public function __construct() {
parent::__construct();
$this->load->library('FusionCharts');
}
public function index() {
$this->load->view('charts_index');
}
public function getData($year='2010') {
// Instantiate the FusionCharts object
$FC = new FusionCharts();
// specify the graph parameters
$strParam="caption=Quarterly Sales for ".$year.";xAxisName=Quarter;yAxisName=Revenue;numberPrefix=$;decimalPrecision=0;formatNumberScale=1";
$FC->setChartParams($strParam);
// specify the data bsaed on the $year parameter
if ($year=='2010') {
$FC->addChartData("40800","name=Q1");
$FC->addChartData("31400","name=Q2");
$FC->addChartData("26700","name=Q3");
$FC->addChartData("54400","name=Q4");
} else {
$FC->addChartData("800","name=Q1");
$FC->addChartData("400","name=Q2");
$FC->addChartData("700","name=Q3");
$FC->addChartData("200","name=Q4");
}
// output the FusionCharts XML
print $FC->getXML();
}
}
?>
and the view is like this
<html>
<head>
<title>Dynamic Graphs with JQuery and FusionCharts</title>
<script language="JavaScript" src="/public/js/FusionCharts.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script language="JavaScript">
function drawChart(chartSWF, strXML, chartdiv) {
//Create another instance of the chart.
var chart = new FusionCharts(chartSWF, "chart1Id", "400", "300", "0", "0");
chart.setDataXML(strXML);
chart.render(chartdiv);
}
function updateChart() {
//call the CI data url
$.get('/charts/getData/'+$('#changeData').val(), function(data) {
if ($('#changeChart').val()==='3d') {
drawChart("/public/fscharts/FCF_Column3D.swf", data,"chart1div");
} else {
drawChart("/public/fscharts/FCF_Column2D.swf", data,"chart1div");
}
});
}
$(document).ready(function(){
//create the chart initially
$.get('/charts/getData/', function(data) {
drawChart("/public/fscharts/FCF_Column3D.swf", data, "chart1div");
});
//update the chart if the dropdown selection changes
$('#changeChart').change(function() {
updateChart();
});
$('#changeData').change(function() {
updateChart();
});
});
</script>
</head>
<body>
<select name="changeData" id="changeData">
<option value="2010" selected>2010</option>
<option value="2009">2009</option>
</select>
<select name="changeChart" id="changeChart">
<option value="3d">3D Version</option>
<option value="2d">2D Version</option>
</select><br>
<div id="chart1div" align="left">The chart will appear within this DIV. This text will be replaced by the chart.</div>
</body>
</html>
hope this will help you other wise visit this site...
Click ON this for More Help