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

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

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

How can I fetch autocomplete data into their respected element using Ajax and Laravel?

Here is my problem.
I'm trying to fetch the data from an auto-completing text-box.
There are two text-boxes:
Region and province.
I have successfully fetched the data on the text-box having region as name.
My problem is, it gives the same value to the next text-box having province as name.
In my Laravel blade I have this code:
<input id="region" type="text" class="form-control" name="region" value="" required autofocus>
<div id="regionList"> </div>
<input id="province" type="text" class="form-control" name="province" value="" required autofocus>
<div id="provinceList"> </div>
I have also a javascript file named auto-complete
$(document).ready(function() {
$('#region').keyup(function() {
var region = $(this).val();
if (region != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url: "register/showRegion",
method: "POST",
data: { region: region, _token: _token },
success: function(data)
{
$('#regionList').fadeIn();
$('#regionList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
$('#province').keyup(function() {
var province = $(this).val();
if (province != '')
{
var _prov_token = $('input[name="_token"]').val();
$.ajax({
url: "register/showProvince",
method: "POST",
data: { province: province, _token: _token },
success: function(data)
{
$('#provinceList').fadeIn();
$('#provinceList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
});
And on my routes I included this
Route::post('/register/showRegion', 'LocationController#showRegion');
Route::post('/register/showProvince', 'LocationController#showProvince');
And on my controller is this
public function index() {
return view('auth.register');
}
function showRegion(Request $request)
{
if ($request->get('region'))
{
$region = $request->get('region');
$regions = Refregion::where('regDesc', 'LIKE', "$region%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($regions as $region)
{
$output .= '<li>'.$region->regDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
function showProvince(Request $request)
{
if ($request->get('province'))
{
$province = $request->get('province');
$province = Refprovince::where('provDesc', 'LIKE', "province%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($provinces as $province)
{
$output .= '<li>'.$province->provDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
I'm trying to figure out why it gives the same value to the other text-box "province" when I have selected region.
Can someone help me with this, or at least explain to me why this happen?
Thank you
change it
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
on this
$('#regionList').on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
and change it
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
on this
$('#provinceList').on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});

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

How to upload photo using Laravel RestApi and vuejs

I'm working on a RestFulApi using Laravel and Vuejs, now want upload a photo using RestfulApi and vuejs. Here comes my sample code:
<div class="form-group form-group-default float-left required">
<label for="photo">Photo</label>
<input class="file-input" type="file" ref="photo" name="photo" v-
on:change="addFile($event)">
</div>
data(){
return{
films_info:
{
photo: null,
}
}
},
methods: {
addFile: function(e){
let that = this;
that.films_info.photo = this.$refs.photo.files[0];
},
saveFilms: function(){
let that = this;
axios.post('/api/films/save_films',that.films_info)
.then(function (response) {
location.reload(true);
})
.catch(function (error) {
that.errors = error.response.data.errors;
console.log("Error Here: "+error.response.data);
});
}
}
protected function saveFilms(Films $request)
{
if ( $request->photo ) {
$extension = $filmsObj->photo->getClientOriginalExtension();
$request->photo = 'films_'.\Carbon\Carbon::now().'.'.$extension; // renaming image
$request->photo->move($dir_path, $request->photo);
}
}
Here in this code I get error in getClientOriginalExtension() method call. It says:
getClientOriginalExtension() method called on string.
Finally I managed to solved the photo upload issue using VueJS and Laravel Api call.
<div class="form-group form-group-default float-left required">
<label for="file">File</label>
<input class="file-input" type="file" ref="file" name="file" v-
on:change="addFile($event)">
</div>
data(){
return{
films_info:
{
file: null,
}
}
},
methods: {
addFile(e){
this.films_info.file = this.$refs.file.files[0];
},
saveFilms(){
let formData = new FormData();
formData.append('file', this.films_info.file);
axios.post('/api/films/save_films',formData,{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
location.reload(true);
})
.catch(error => {
that.errors = error.response.data.errors;
console.log("Error Here: "+error.response.data);
});
}
}
$dir_path = 'uploads/films/images';
$dir_path_resize = 'uploads/films/images/45x45';
if( $request ){
$filmsObj = new Film();
if (!File::exists($dir_path))
{
File::makeDirectory($dir_path, 0775, true);
}
if (!File::exists($dir_path_resize))
{
File::makeDirectory($dir_path_resize, 0775, true);
}
if ( $request->file ) {
$file = $request->file;
$extension = $file->getClientOriginalExtension(); // getting image extension
$file_name = 'films_'.\Carbon\Carbon::now().'.'.$extension; // renaming image
$file->move($dir_path, $file_name); // uploading file to given path
// Start : Image Resize
$image = Image::make(public_path($dir_path.'/'.$file_name));
// resize the image to a height of 45 and constrain aspect ratio (auto width)
$image->resize(null, 45, function ($constraint) {
$constraint->aspectRatio();
});
$image->save(public_path($dir_path_resize.'/'.$file_name));
// End : Image Resize
}

submit form from <div> html value in codeigneter

i have problem using form in codeigneter when to submit value from div html,
example view
<label for="title">Title:</label>
<input type="text" class="form_field" id="title" name="title" size="30" value="<?php echo set_value('title', isset($default['title']) ? $default['title'] : ''); ?>" />
<div class="form_field" name="contentbox" id="contentbox" contenteditable="true">
<?php echo set_value('contentbox', isset($default['contentbox']) ? $default['contentbox'] : ''); ?></div>
in div id="contentbox" is set contenteditable="true", and i will get dinamic value,
controller
....
$data = array( 'title' => $this->input->post('title'),
'content' => $this->input->post('contentbox'));
$this->my_model->add($data);
....
but in controller i can't get value div id="contentbox" , i have problem input to database,when i'm typing "sometext" in div id="contentbox" value always "0"
You can use the jquery cookie plugin to grab CI csrf token and include it before this function
jQuery
(function($){
var do_ajax = function(data, scope){
// depending on your version of CI csrf token name will differ
// newer versions of CI use the name in your application/config file
data = {content : data, csrf_token : $.cookie('csrf_token')}
$.ajax({
url : BASE_PATH + 'some_class/some_method',
data: data,
context : scope,
type : 'POST',
dataType : 'json',
success : function(callback){
//check the status first!
var $this = $(this);
$this.find(".msg").fadeIn();
$this.find("#contentbox").html(data);
}
});
}
var contents = {
init: function(){
if($("#editme"))
this.contentEditable();
},
contentEditable : function(){
var scope = $("#editme"),
eicon = $(".icon-editable").hide(),
emessage = $(".msg").hide(),
econtent = $("#contentbox");
econtent.hover(function(){
eicon.show();
}, function(){
eicon.hide();
});
econtent.blur(function(){
do_ajax($(this).html(), scope);
});
}
}
$(function(){
contents.init();
});
})(jQuery);
HTML
<div id="editme" class="editme">
<span class="icon-editable">✎</span>
<span class="msg">Content updated!</span>
<h4>Some relevant title</h4>
<div id="contentbox" class="contentbox" contenteditable="true">
This is editable...
</div>
</div>
CSS
div.editme{
position:relative;
background:#ffffff;
padding:30px 8px 8px 8px;
}
span.icon-editable, span.msg{
position:absolute;
top:0;
}
span.icon-editable{
left:0;
border:1px solid #d1d1d1;
border-top:0;
border-left:0;
font-size:1em;
line-height:1.2em;
}
span.msg{
right:0;
font-size:0.8em;
line-height:1.2em;
color:#fafafa;
background:green;
padding:3px;
}
PHP
class some_class extends Controller{
public function some_method(){
if($this->input->is_ajax_request())
{
$data = array(
'content' => $this->input->post('content')
);
if($this->my_model->add($data))
{
$responce = array(
'status' => 'ok'
);
}
else
{
$responce = array(
'status' => 'notok'
);
}
echo json_encode($responce);
}
else
{
show_404();
}
}
}
Test version without ajax request
CLICK HERE

Resources