how can I change pdf from datatable for pdf for serverside html2pdf? - jquery-plugins

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

Related

Highcharts Data filtering can't populate MySQL PHP

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 ?

Anyone can tell me whats wrong in here when im putting a array of number like :1,2 its starting to freeze the screen i hope someone can help me thanks

Hello guys im trying to learn vue and im trying to use datatable from https://datatables.net/ and having a problem with my action button that im not able to get the id when the #viewModal is been triggered i hope someone can help me to get the id of each buttons thanks and here is my code TIA:
EmployeeDataTable Component :
<template>
<div class="card">
<div class="card-header">
<div class="card-title">Employee List</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table
id="employee-table"
class="table-sm table-bordered table-hover text-center display"
width="100%"
>
<thead>
<tr>
<th class="pt-3 pb-3">#</th>
<th>Name</th>
<th>Address</th>
<th>Contact #</th>
<th>Department</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</template>
<script>
//For Datatable to work
import "datatables.net";
import EmployeeEdit from "./EmployeeEdit.vue";
export default {
name: "EmployeeList",
data() {
return {
employees: [],
};
},
mounted() {
this.getEmployeeLists();
},
components: {
"employee-edit": EmployeeEdit,
},
methods: {
getEmployeeLists() {
// INITIALIZE DATATABLE
$("#employee-table")
.DataTable({
//LOADING
// processing: true,
//AJAX
serverSide: true,
//DIRECTION
order: [[1, "desc"]],
//AJAX
ajax: {
url: "/api/getEmployeeLists",
dataList: "json",
type: "POST",
data: { _token: "{{csrf_token()}}" },
},
//TABLE COLUMNS SHOULD BE THE SAME IN CONTROLLER
columns: [
{ data: "#" },
{ data: "name" },
{ data: "address" },
{ data: "contact" },
{ data: "department" },
{ data: "status" },
{
data: "actions",
//allowing modification
createdCell(cell, cellData, rowData) {
let EmployeeListDataTableActions = Vue.extend(
require("./EmployeeListDataTableAction.vue").default
);
let instance = new EmployeeListDataTableActions().$mount();
$(cell).empty().append(instance.$el);
},
},
],
//View Count in Table
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"],
],
})
.columns();
},
beforeDestroy: function () {
$(this.$el).DataTable().destroy();
},
},
};
</script>
EmployeeDataTableAction Component :
<template>
<button class="btn btn-primary btn-sm" #click="viewModal" title="View Employee Details">
<i class="fa fa-eye"></i>
</button>
</template>
<script>
export default{
name: 'EmployeeListDataTableAction',
data: function() {
return {
}
},
mounted() {
},
methods: {
viewModal() {
var id = $(this.$el).closest('tr').find('input').val();
return false;
axios
.post(`/api/getEmployeeDetails/${id}`, {
id: id,
})
.then((response) => {
$("#edit-employee-modal").modal("show");
$(".myModalLabel").text(
response.data.name +
" - " +
response.data.department_name
);
state.commit("getEmployeeDetailsArray", response.data);
state.commit("getTransactionId", response.data.id);
})
.catch((response) => {
this.$toast.top("Something went wrong!");
});
},
},
}
</script>
Employee Controller for the DataTable :
public function employeeList(Request $request){
$all = Employee::getEmployeeTotal();
//total count of data
$total_data = $all;
//total filter
$total_filtered = $total_data;
//set_time_limit(seconds)
$limit = $request->input('length');
//start
$start = $request->input('start');
//order
// $order = $columns[$request->input('order.0.column')];
//direction
$dir = $request->input('order.0.dir');
$search_value = $request->input('search.value');
if (!empty($search_value)) {
$posts = Employee::getEmployeeNameSearch($search_value,$start, $limit, $dir);
$total_data = count($posts);
$total_filtered = $total_data;
}else{
if(empty($request->input('search.value')))
{
//if no search
$posts = Employee::getEmployeeList($start, $limit, $dir);
}
}
$data = array();
if(!empty($posts))
{
$counter = $start + 1;
foreach ($posts as $post)
{
$department = GlobalModel::getSingleDataTable('departments',$post->department_id);
$status = StatusController::checkStatus($post->status);
$nested_data['#'] = '<span style="font-size: 12px ; text-align: center;">'.$counter++.'</span>';
$nested_data['name'] = '<p style="text-align: center;">'.$post->name.'</p>';
$nested_data['address'] = '<p style="text-align: center;">'.$post->address.'</p>';
$nested_data['contact'] = '<p style="text-align: center;">'.$post->contact.'</p>';
$nested_data['department'] = '<p style="text-align: center;">'.$department->name.'</p>';
$nested_data['status'] = '<p style="text-align: center;">'.$status.'</p>';
$nested_data['actions'] = '';
$data[] = $nested_data;
}
}
$json_data=array(
"draw" => intval($request->input('draw')),
"recordsTotal" => intval($total_data),
"recordsFiltered" => intval($total_filtered),
"data" => $data
);
return response()->json($json_data);
}
In the second line of your viewModal() function, you are placing a return false; statement. "The return statement ends function execution and specifies a value to be returned to the function caller." From Mozilla docs. That's why the API call is never executing.

I need the data ,according to the type I send

My view blade that displays the data of all types but I need the specific type only, where i send it by ajax: "{{ route('taxonomies.json',type) }}".How do I send the type that I want from the given type?
<div class="table">
<table id="taxonomyTable">
<thead>
<tr>
<th>SN</th>
<th>Title</th>
<th>Parent</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="quickModal" tabindex="-1" role="dialog" aria-labelledby="quickModal" aria-hidden="true">
</div>
<input type="hidden" id="type" value="{{ $type }}" />
and the js is:
<script>
$(document).ready(function () {
var type = $('#type').val();
$('#taxonomyTable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('taxonomies.json') }}",
columns: [
{
data: 'id',
render: function (data, type, row) {
return '<strong> #' + data + '</strong>';
}
},
{
data: 'title', name: 'title',
render: function (data, type, row) {
return '<strong>' + data + '</strong>';
}
},
{
data: 'parent', name: 'parent',
render: function (data, type, row) {
return '<strong>' + data.title + '</strong>';
}
},
{
data: 'type', name: 'type',
render: function (data, type, row) {
return '<strong>' + data.type+ '</strong>';
}
},
{
data: 'status',
render: function (data, type, row) {
return data === 'Active' ? '<button class="btn btn-outline-success btn-update-status" data-id="' + row.id + '">Active</button>' : '<button class="btn btn-xs btn-outline-danger btn-update-status" data-id="' + row.id + '">Inactive</button>';
}
},
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
});
</script>
and my route is:
Route::get('/taxonomies/taxonomy-json/{type}', 'Admin\TaxonomyController#taxonomyJson')->name('taxonomies.json');
and my TaxonomyController has:
public function taxonomyJson()
{
$taxonomy = Taxonomy::with('parent')->toJson();
return DataTables::of($taxonomy)
->addIndexColumn()
->addColumn('action', function ($taxonomy) {
return '<div class="table-actions float-left">
<i class="ik ik-edit-2 green"></i>
<i class="ik ik-trash-2 red"></i>
</div>';
})->make();
}
The code mentioned above displays all of the types in the data but I only need the data of given type.Like my types are category, tag, videos,slider,etc and I need the data of types category only.
How can I fetch it?
Change You Input Hidden tag to which include whole route with it's parameters
<input type="hidden" id="type" value="{{ route('taxonomies.json', ['type' => $type]) }}" />
Now, In Your Ajax call pass input hidden type value directly to ajax as url.
var type_url = $('#type').val();
ajax: type_url
This way you don't have to worry about passing dynamic param. value to JS code from PHP code.
& In Your Controller Function
public function taxonomyJson($type=null)
{
$taxonomy = Taxonomy::with('parent')
if ($type) {
$taxonomy = $taxonomy->where('type', $type);
}
$taxonomy = $taxonomy->toJson();
return DataTables::of($taxonomy)
->addIndexColumn()
->addColumn('action', function ($taxonomy) {
return '<div class="table-actions float-left">
<i class="ik ik-edit-2 green"></i>
<i class="ik ik-trash-2 red"></i>
</div>';
})->make();
}
From your question as far I understood that you want filtered data, in order to get filtered data you needed to pass a filter type which you must use to filter your query. Here is an example for you
if ($request->ajax()) {
$users = User::select(
'users.id',
'users.name',
'users_details.first_name',
'users_details.last_name',
'users.email',
'users.membership_no',
'users.is_active',
'users.created_at'
)
->leftJoin('users_details', 'users.id', '=', 'users_details.users_id')
->where('user_group', '<>', 'admin')
->where(function ($query) use ($request) {
$genery = $request->get("genere");
$varsitySession = $request->get("varsity_session");
$yearOfPassing = $request->get("year_of_passing");
$department = $request->get("department");
$bloodGroup = $request->get("blood_group");
$membership = $request->get("membership");
if (isset($genery) && $genery) {
$query->where('users_details.genre', $genery);
}
if (isset($varsitySession) && $varsitySession) {
$query->where('users_details.varsity_session', $varsitySession);
}
if (isset($yearOfPassing) && $yearOfPassing) {
$query->where('users_details.year_of_passing', $yearOfPassing);
}
if (isset($department) && $department) {
$query->where('users_details.department', $department);
}
if (isset($bloodGroup) && $bloodGroup) {
$query->where('users_details.blood_group', $bloodGroup);
}
if (isset($membership) && $membership) {
$query->where('users_details.membership', $membership);
}
if (isset($request->requested) && $request->requested == 0) {
$query->where('users.membership_no', $request->requested);
}
})
->get();
return Datatables::of($users)
->editColumn('name', function ($users) {
return ($users->first_name) ? $users->first_name . ' ' . $users->last_name : $users->name;
})
->editColumn('is_active', function ($users) {
return ($users->is_active) ? 'Active' : 'De-active';
})
->editColumn('membership_no', function ($users) {
return ($users->membership_no) ? $users->membership_no : 'Not Assigned';
})
->editColumn('created_at', function ($users) {
return $users->created_at->toDayDateTimeString();
})
->make(true);
}
Here you can see that I'm generating a query with where clause which are generated from request data
$genery = $request->get("genere");
$varsitySession = $request->get("varsity_session");
$yearOfPassing = $request->get("year_of_passing");
$department = $request->get("department");
$bloodGroup = $request->get("blood_group");
$membership = $request->get("membership");
Here genere,varsity_session,year_of_passing,department,blood_group,membership are my filter data I'm sending with request.
here is my data table code
$('.dataTable').dataTable({
destroy: true,
paging: true,
searching: true,
sort: true,
processing: true,
serverSide: true,
"ajax": {
url: '{{ url('users/datatable')}}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
'data': function (d) {
d.genere = $("#genere").val();
d.varsity_session = $("select[name = varsity_session]").val();
d.year_of_passing = $("select[name = year_of_passing]").val();
d.department = $("select[name = department]").val();
d.blood_group = $("input[name = blood_group]").val();
d.membership = $("select[name = membership]").val();
d.paymentStatus = $("select[name = paymentStatus]").val();
d.requested = $("select[name = requested]").val();
}
},
"columns": [
{data: 'id'},
{data: 'name'},
{data: 'email'},
{data: 'membership_no'},
{data: 'is_active'},
{data: 'varsity_session'},
{data: 'due_amount'},
{data: 'paid_amount'},
{data: 'created_at'},
{data: 'last_transaction_date'},
{data: 'action'},
],
"columnDefs": [
{"bSortable": false, "targets": [1, 6]},
{"searchable": false, "targets": [4, 6]}
],
lengthMenu: [[10, 50, 100, -1], [10, 50, 100, "All"]],
pageLength: 10,
"dom": 'Blfrtip',
buttons: [
{
extend: 'copy',
text: 'copy',
className: 'btn btn-primary',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'csv',
text: 'csv',
className: 'btn btn-warning',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'excel',
text: 'excel',
className: 'btn btn-danger',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'pdf',
text: 'pdf',
className: 'btn btn-success',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'print',
text: 'print',
className: 'btn btn-btn-info',
exportOptions: {
columns: 'th:not(:last-child)'
}
}
]
});
});
And my Static Html code
<div class="row">
<div class="col-lg-12">
<div class="table-responsive">
<table class="display compact dataTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Membership No</th>
<th>Status</th>
<th>Versity Session</th>
<th>Due Amount</th>
<th>Paid Amount</th>
<th>Created At</th>
<th>Last Transaction</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!-- /.col-lg-12 -->
</div>

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

Laravel ajax respond appending to body but not to #results

I have problem with outputting results from search in a div with id 'results' if I append the results to body they show up but when I change it to #results it's never appearing.
Search box is in navigation in master.blade.php and every other page includes it.
master.blade.php
<form id="search_form" action="/search" method="get" autocomplete="off" class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value);" placeholder="Search">
</div>
<div id="result">
<table style="width:100%">
#if (isset($results) && count($results) > 0)
#foreach( $results as $business )
<tr>
<td>{{ $business->logo }}</td>
<td>{{ $business->name}}</td>
</tr>
#endforeach
#endif
</table>
</div>
</div>
</form>
Controller:
public function search($search_value) {
$search_text = $search_value;
if ($search_text==NULL) {
$data= Business::all();
} else {
$data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
}
//$data = $data->toArray();
return view('master')->with('results',$data);
}
Ajax:
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
type: 'post',
dataType: 'html',
success: function(data) {
$('#results').append(data);
},
error: function(data) {
$('body').html(data);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
Route::
Route::post('/searching/{search}', 'SearchController#search');
If I actually look into ajax response, result is there:
<table style="width:100%">
<tr>
<td></td>
<td>dasd</td>
</tr>
</table>
But it never appears on the page! It does if the append is changed to body.
//edit
I have a loading gif which worked fine but now it never dissapears and each time it executed ajax, it doesn't want to dissapear too:
$(document).ajaxStart(function() { Pace.restart(); });
$(window).on('load', function () {
setTimeout(function(){
$('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
});
}); // set the time here
});
$(document).ready(function() {
setTimeout(function() {
$(".messages").fadeOut(5000);
});
setTimeout(function() {
$(".messages").fadeOut(5000);
});
});
css:
.se-pre-con {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
opacity: 0.5;
background-color: #6d6968;
background: url(../images/default.gif) center no-repeat #fff;
}
jQuery.ajaxSetup({
beforeSend: function (xhr, data) {
$('.se-pre-con').show();
},
complete: function ()
{
$('.se-pre-con').hide();
}
});

Resources