Display image in codeigniter datatable - ajax

Controller : here productlist2() just call the view page .
function productlist2()
{
$this->load->view("admin/bill/datatable.php", array());
}
public function productlist_page()
{
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$books = $this->Category_model->get_all_product_datatable();
$data = array();
foreach($books->result() as $r) {
$data[] = array(
$r->categoryID,
$r->productName,
$r->costPrice,
$r->salesPrice,
$r->unit,
$r->origin,
$r->files
);
}
$output = array(
"draw" => $draw,
"recordsTotal" => $books->num_rows(),
"recordsFiltered" => $books->num_rows(),
"data" => $data
);
echo json_encode($output);
exit();
}
After ajax calling the productlist_page() function this productlist_page() gets the value from model.
View:
<table id="book-table" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<td>ID</td>
<td>Product Name</td>
<td>Cost Price</td>
<td>Sales Price</td>
<td>Unit</td>
<td>Description</td>
<td>Picture</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here is my js script code.
<script type="text/javascript">
$(document).ready(function() {
$('#book-table').DataTable({
"ajax": {
url : "<?php echo site_url("admin/category/productlist_page") ?>",
type : 'GET'
},
});
});
</script>
Here , in picture column i want to show images , only the string value is there as output in files column . Question is how can i show the image ?

Related

DataTables Server-side Processing in CodeIgniter but data is not display in table

I can print the data out but data is not displayed in the table.
I'm trying to use Datatable to display the data.
Here are error messages:
DataTables warning: table id=example - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
model
function allposts_count()
{
$query = $this
->db
->get('books');
return $query->num_rows();
}
function allposts($limit,$start,$col,$dir)
{
$query = $this
->db
->limit($limit,$start)
->order_by($col,$dir)
->get('books');
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return null;
}
}
controller
function Book()
{
$columns = array(
0 =>'id',
1 =>'title',
);
$limit = $this->input->post('length');
$start = $this->input->post('start');
$columns=$this->input->post('order')[0]['column'];
$order = $columns;
$dir = $this->input->post('order')[0]['dir'];
$totalData = $this->user_model->allposts_count();
$totalFiltered = $totalData;
if(empty($this->input->post('search')['value']))
{
$posts = $this->user_model->allposts($limit,$start,$order,$dir);
}
else {
$search = $this->input->post('search')['value'];
$posts = $this->user_model->posts_search($limit,$start,$search,$order,$dir);
$totalFiltered = $this->user_model->posts_search_count($search);
}
$data = array();
if(!empty($posts))
{
foreach ($posts as $post)
{
$nestedData['id'] = $post->book_id;
$nestedData['title'] = $post->book_title;
$data[] = $nestedData;
}
}
$json_data = array(
"draw" => intval($this->input->post('draw')),
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalFiltered),
"data" => $data
);
$json = json_encode($json_data);
echo $json;
$this->load->view('templates/header');
$this->load->view('users/Book',$json);
$this->load->view('templates/footer');
}
view
<div class="container">
<h1>Server Side Process Datatable</h1>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</tfoot>
</table>
<!--create modal dialog for display detail info for edit on button cell click-->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div id="content-data"></div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
var dataTable=$('#example').DataTable({
"processing": true,
"serverSide":true,
"ajax":{
"url": "<?php echo base_url('users/Book') ?>",
"dataType": "json",
"type": "POST",
"data":{ '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>' }
},
"columns": [
{ "data": "book_id" },
{ "data": "book_title" },
]
});
});
</script>
datatables expects a pure json response. if you followed the debugging steps in the link you posted you would have seen that your response also contains a view.
here you have json then a view:
$json = json_encode($json_data);
echo $json;
$this->load->view('templates/header');
$this->load->view('users/Book',$json);
$this->load->view('templates/footer');
remove the views and/or move the json stuff to another url. then update "url": "<?php echo base_url('users/Book') ?>", to the new url.
you should echo $data to show data in table #example.
<table id="example" cellpadding="0" cellspacing="0">
<thead><tr>
<th>ID</th>
<th>Name</th>
</tr></thead>
<tbody>
<!-- rows will go here -->
</tbody>
</table>
And in javascript
$("#example tbody").html(someHtmlString);
You dont have tbody to put return query in your code.
And debug to check if the data is valid or not.

Real Live Search and Filter Laravel

I'm new on Laravel and try to implement real live search and filter on my project, but it doesn't work at all. I dont understand ajax ver much and just copy paste the code from other website. I tried to understand the code and I think its correct but it doesn't work, so please help. Thanks
Here is my controller
public function search(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = Service::table('service')
->where('keterangan', 'like', '%'.$query.'%')
->orWhere('biaya', 'like', '%'.$query.'%')
->get();
}
else
{
$data = Service::table('service')
->orderBy('kodeService', 'asc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->kodeService.'</td>
<td>'.$row->keterangan.'</td>
<td>'.$row->biayaService.'</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output
);
echo json_encode($data);
}
}
This is the script
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('live_search.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('#table tbody').html(data.table_data);
}
});
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query)
});
});
Route :
Route::resource('service', 'ServiceController');
Route::get('service/search', 'Service#search')->name('live_search.action');
And index.blade
<table class="table table-striped table-hover table-bordered" id="table">
<thead>
<tr>
<th>Kode Service</th>
<th>Keterangan</th>
<th>Biaya</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
#foreach($service as $data)
<tr>
<td><?= $data->kodeService?></td>
<td><?= $data->keterangan ?></td>
<td><?= $data->biayaService?></td>
<td>
<a class="btn btn-sm btn-info" href="{{ route('service.edit', $data['kodeService']) }}"> <i class="oi oi-pencil"></i> Edit</a>
<button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#myModal"><span class="oi oi-trash"></span> Hapus</button>
</td>
</tr>
#endforeach
</tbody>
</table>
Put your route like this :
Route::get('service/search', 'ServiceController#search')->name('live_search.action');
Route::resource('service', 'ServiceController');
After that open the Browser Console panel (Press F12 to open it) and check the Ajax request in Network tab.
Where you can get the specific error if any in the Response tab.
If you need an extra route to your resource route,you should place the new route before the resource route.
Route::get('service/search', 'ServiceController#search')->name('live_search.action');
Route::resource('service', 'ServiceController');

Could not open for reading! File does not exist Phpexcel with laravel

I have a problem with read file .xls when I using phpexcel-laravel. Im using phpexcel at here https://github.com/Maatwebsite/Laravel-Excel, and I want to read data in file .xls . My .xls have 2 column, column id and column name, I run function getFile and I got message error is "Could not open for reading! File does not exist". I dont know how to fix that. Can you direct me? Thanks you!
My controller:
public function getFile(){
$results=array();
Excel::load('file/test.xls', function($reader) {
$results = $reader->select(array('id', 'name'))->get()->toArray();
});
$data = array(
'results' = $results;
);
return View::make('show_excel',$data)->render();
}
My view:
#if(!empty($results))
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>name</th>
</tr>
</thead>
#foreach ($results as $row)
<tr>
<td>{{$row->id}}</td>
<td>{{$row->name}}</td>
</tr>
#endforeach
</table>
#endif
public function getFile(){
$data = Excel::load('file/test.xls', function($reader) {})->get();
if(!empty($data) && $data->count()){
foreach ($data->toArray() as $key => $value) {
$insert[] = ['id' => $value['id'], 'name' => $value['name']];
}
if(!empty($insert)){
Item::insert($insert);
return back()->with('success','Insert Record successfully.');
}
}
}
Use full file path.

Image upload to specific folder in codeigniter

I've been trying to upload images to specific folder my scenario is I've upload controller in which I've do_upload function
public function do_upload($field_name) {
$field_name = 'image_title';
$page_id = $this->input->post('page_id');
$config = array(
'allowed_types' => '*',
'max_size' => '1024',
'max_width' => '1024',
'max_height' => '768',
'upload_path' => './uploads/'. $page_id
);
$this->load->library('upload');
$this->upload->initialize($config);
if (!is_dir('uploads'))
{
mkdir('./uploads/', 0777, true);
}
$dir_exist = true; // flag for checking the directory exist or not
if (!is_dir('uploads/' . $page_id))
{
mkdir('./uploads/' . $page_id, 0777, true);
$dir_exist = false; // dir not exist
}
else{
}
if (!$this->upload->do_upload($field_name)) {
if(!$dir_exist)
rmdir('./uploads/' . $page_id);
$this->data['error'] = array('error' => $this->upload->display_errors());
} else {
$fInfo = $this->upload->data($field_name);
$this->_createThumbnail($fInfo['file_name']);
return $fInfo;
}
}
/**********************************************************************************************/
function _createThumbnail($filename)
{
$config['image_library'] = "gd2";
$config['source_image'] = "uploads/" .$filename;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = "80";
$config['height'] = "80";
$this->load->library('image_lib',$config);
if(!$this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
I've index view file given as
<section>
<?php echo validation_errors(); ?>
<?php //echo form_open_multipart('admin/upload/index/' . ((isset($page->id)) ? $page->id : '' )); ?>
<?php echo form_open_multipart('admin/upload/index/'); ?>
<tr>
<td><h3>Upload Images</h3></td>
</tr>
<table class="table table-striped">
<tr>
<thead>
<tr>
<th>Image Name</th>
<th>View</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php if (count($images)): foreach ($images as $image): ?>
<tr>
<td><?php echo anchor('admin/upload/index/' . $image->id, $image->image_title); ?></td>
<td><?php echo btn_edit('admin/upload/index/' . $image->id); ?></td>
<td><?php echo btn_delete('admin/upload/index/' . $image->id); ?></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="3">There is no Image to display</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</section>
<section>
<table class="table table-striped">
<tbody>
<tr>
<td><h5>Select Page</h5></td>
<td><?php echo form_dropdown('page_id', $get_with_images, $this->input->post('page_id')); ?></td>
</tr>
<tr>
<td><h5>Select Image</h5></td>
<td>
<?php echo form_upload('image_title', set_value('image_title', $image->image_title)); ?>
</td>
</tr>
<tr>
<td><?php echo form_submit('submit', 'Upload', 'class="btn btn-success"'); ?></td>
</tr>
</tbody>
</table>
<?php echo form_close(); ?>
</section>
dropdown is populating from page controller what actually I needed is I want to upload image to the page selected from dropdown for example if "Contact" page is selected from dropdown I want to upload my image to "Contact" page and on the backend I want to create directory with the same name as selected in dropdown in my case I want "uploads/home/abc.jpg" and same for the other pages please advice the basic idea I will modify it with my own
You're already sending your pageid value as post. Use it at uploading config.
...
$config = array(
...
'upload_path' => './upload/' . $this->input->post('page_id')
)
You need to check if directory exists first, use isdir() PHP function, and if false, mkdir(), also PHP, with folder name and permission.
I'm not familiar anymore with CodeIgniter to tell you if there is some way to get written value of a <option> tag, but I would suggest to create a array with page ids and their respective name and look for the array's index by post value:
$page_name = [
0 => 'contact',
1 => 'home',
2 => 'user',
...
]
...
$config = array(
...
'upload_path' => './upload/' . $page_name[$this->input->post('page_id')]
)
EDIT: User had problems with thumb creation
With your update, you forgot to update also path of the thumbnail. So you must send the folder and filename:
function _createThumbnail($folder, $filename)
{
$config['image_library'] = "gd2";
$config['source_image'] = "./uploads/" $folder . "/" .$filename;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = "80";
$config['height'] = "80";
$this->load->library('image_lib',$config);
if(!$this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
Then you should call it as you were, replacing the parameters correctly:
$this->_createThumbnail($page_id, $fInfo['file_name']);

Joomla 2.5 displaying data /multiple rows in view

I'm new to joomla development. After having managed to directly list database multiple rows directly into the conttroller, i'm trying to display it using views, but i have an error message :
Controller :
function display($cachable = false, $urlparams = false)
{
// Affichage de la liste des tournois
$db=JFactory::getDBO();
$sql="select * from #__tournois_tournois";
//echo $sql;
$db->setQuery($sql);
$db->query();
$items=$db->loadobjectList();
// set default view if not set
$input = JFactory::getApplication()->input;
$input->set('view', $input->getCmd('view', 'Tournois'));
// call parent behavior
parent::display($cachable);
in my view :
function display($tpl = null)
{
// Get data from the model
$items = $this->get('Items');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
// Assign data to the view
$this->items = $items;
// Set the toolbar
$this->addToolBar();
// Display the template
parent::display($tpl);
}
In the default tpl :
<form action="<?php echo JRoute::_('index.php?option=com_tournoi&ask=edit'); ?>" method="post" name="adminTournoisForm" id="adminTournoisForm">
<table class='adminlist'>
<thead>
<tr>
<th width='1%'> </th>
<th class='title'>ID</th>
<th class='title'>Tournoi</th>
<?
foreach ($this->items as $i => $item)
{
//$row=$rows[$i]?>
<tr>
<th><? echo $item->tournois_id?></th>
<th><? echo $item->tournois_title?></th>
</tr>
<?}?>
</table>
</form>

Resources