Real Live Search and Filter Laravel - ajax

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

Related

Using v-for in laravel + vue.js, am trying to display a table containing information of the user but nothing shows

<script>
export default {
name: "OutPatient",
data(){
return{
out_patients: {}
}
},
methods: {
index(){
axios.get('/data/out_patient').then(({data}) =>
(this.out_patients = data.data));
},
update(){}
},
created(){
this.index();
}
}
</script>
<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
<td>{{out_patient.id}}</td>
<td>{{out_patient.first_name}}</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<i class="fa fa-edit blue"></i>
|
<i class="fa fa-trash red"></i>
</td>
</tr>
This is my code but the data is not showing in the table even though in the XHR the data shows there.
In the inspect element I can see the data but the v-for loop is unable to display the data.
Seems to me like you tried to extract data twice, you have this:
axios.get('/data/out_patient').then(({data}) =>
(this.out_patients = data.data));
if you already extract it here: {data} then you don't need data.data, only data below?
index() {
this.error = this.out_patients = null;
this.loading = true;
axios
.get('/data/out_patient')
.then(response => {
this.loading = false;
this.out_patients = response.data;
}).catch(error => {
this.loading = false;
this.error = error.response.data.message || error.message;
});
},
this rather works for me.
thank you all for the support
can you try fetching the data on mounted life cycle hook instead of created in order to populate the table with data on page load mounted is the best hook lifecycle as much I know.
<script>
export default {
name: "OutPatient",
data(){
return{
out_patients: {},
out_patient:'',
}
},
methods: {
index(){
axios.get('/data/out_patient')
.then(({data}) =>
(this.out_patients = data.data));
},
update(){
}
},
created(){
this.index();
}
}
</script>
<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
<td>{{out_patient.id}}</td>
<td>{{out_patient.first_name}}</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<a href="#">
<i class="fa fa-edit blue"></i>
</a>
|
<a href="#">
<i class="fa fa-trash red"></i>
</a>
</td>
</tr>
Just declare out_patient in data. I hope this solves your issue.
And also check if out_patients is returning data.

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.

Display image in codeigniter datatable

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 ?

laravel delete is not working

I am wondering how to put a csrf token in a form so that delete will work?
Here is my code:
Route:
Route::delete('category_delete/{id}',['as'=>'category_delete','uses'=>'CategoryController#destroy']);
index.blade.php
#section('adminContent')
{!! Form::token() !!}
<div class="table-responsive art-content">
<table class="table table-hover table-striped">
<thead>
<th> NAME</th>
<th> ACTIONS</th>
</thead>
<tbody>
#foreach($categoriesView as $category)
<tr>
<td>{!! $category->name!!}</td>
<td>{!! link_to_route('categories.edit', '', array($category->id),array('class' => 'fa fa-pencil fa-fw')) !!}</td>
<td><button type="button" id="delete-button" class="delete-button" data-url = "{!! url('category_delete')."/".$category->id !!}"><i class="fa fa-trash-o"></i></button>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="pagination"> {!! $categoriesView->render() !!}</div>
</div>
#stop
CategoryController:
public function destroy($id,Category $category)
{
$category = $category->find ( $id );
$category->delete ();
Session::flash ( 'message', 'The category was successfully deleted!.' );
Session::flash ( 'flash_type', 'alert-success' );
}
If I used ajax, javascript or jquery, how should the code be?
Using jquery I would do something like the following.
Add the line below in the header of your home view
<meta name="csrf-token" content="{{ csrf_token() }}" />
Now in your javascript
function deleteMe(button)
{
// You might want to put the ajaxSetup function where it will always load globally.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if(confirm("Are you sure?"))
{
$.get(
'category_delete/'+button.id,
function( response )
{
// callback is called when the delete is done.
console.log('message = '+ response.message);
}
)
}
}
In index.blade.php, make your id more specific.
...
<td><button type="button" id=".$category->id" class="delete-button" data-url = "{!! url('category_delete')."/".$category->id !!}"><i class="fa fa-trash-o" onlick="deleteMe(this);></i></button>
...
In your controller
public function destroy($id,Category $category){
$category = $category->find ( $id );
$category->delete ();
return response()->json(
'message' => 'Deleted',
)
}
Note: No need to add
Form::token in your view
Hope this helps.....
Updated...........
If you were to do it using laravel only, I will suggest you use a link rather than the button you are using.
In index.blade.php, make your id more specific.
...
<td><a href="category_delete/".$category->id class="delete-button" data-url = "{!! url('category_delete')!!}"><i class="fa fa-trash-o"></i></td>
...
In your controller
public function destroy($id,Category $category){
$category = $category->find ( $id );
$category->delete ();
return view('index');//important.
}
If you want your link to look like a button, use css or a css framework like bootstrap
That should be it. hope this helps again.

Joomla plugin database mistakes? What is wrong here?

i've just started learning Jplugin development, so here i made a little voting script. Everything here works fine, but i want conf.php file to be made in joomla framework style. As you see here, 1 and 2 files works perfectly together. I want to use third example instead of second, in which i use simple php code. The last example i tried to do is using joomla framework, but it doesnt work. I have no idea what's wrong with that code. Anyone see could tell where I made a mistake or maybe far away from doing it right ?
<?php
defined( '_JEXEC' ) or die;
?>
<?php
class plgSystemRatingx extends JPlugin
{
public function onContentBeforeDisplay()
{
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".like").click(function()
{
var id=$(this).attr("id");
var name=$(this).attr("name");
var dataString = 'id='+ id + '&name='+ name;
$("#votebox").slideDown("slow");
$("#flash").fadeIn("slow");
$.ajax
({
type: "POST",
url: "conf.php",
data: dataString,
cache: false,
success: function(html)
{
$("#flash").fadeOut("slow");
$("#content").html(html);
}
});
});
$(".close").click(function()
{
$("#votebox").slideUp("slow");
});
});
</script>
<body>
<div style="margin:50px">
Like -- Dislike
<div id="votebox">
<span id='close'>X</span>
<div style="height:13px">
<div id="flash">Loading........</div>
</div>
<div id="content">
</div>
</div>
</div>
<?php
return true;
}
}
this piece of code works perfectly
<?php
$mysql_hostname = "localhost";
$mysql_user = "px";
$mysql_password = "px";
$mysql_database = "jum";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
if($_POST['id'])
{
$id=mysql_real_escape_string($_POST['id']);
$name=mysql_real_escape_string($_POST['name']);
mysql_query("update messages set $name=$name+1 where id='$id'");
$result=mysql_query("select up,down from messages where id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['up'];
$down_value=$row['down'];
$total=$up_value+$down_value;
$up_per=($up_value*100)/$total;
$down_per=($down_value*100)/$total;
?>
<div style="margin-bottom:10px">
<b>Ratings for this blog</b> ( <?php echo $total; ?> total)
</div>
<table width="700px">
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $up_value; ?></td>
<td width="600px"><div id="greebar" style="width:<?php echo $up_per; ?>%"></div></td>
</tr>
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $down_value; ?></td>
<td width="600px"><div id="redbar" style="width:<?php echo $down_per; ?>%"></div></td>
</tr>
</table>
<?php
}
?>
and this made in joomla style doesnt work at all
<?php
defined( '_JEXEC' ) or die;
?>
<?php
if(JRequest::getVar('id'))
{
$id = JRequest::getInt('id');
$name = JRequest::getInt('name');
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query2 = $db->getQuery(true);
$queryup = $db->getQuery(true);
$querydown = $db->getQuery(true);
$query->update('messages');
$query->set("message = 1");
$query->where("id = $id");
$query2->select('up,down');
$query2->from('messages');
$query2->where("id = $id");
$queryup->select('up');
$queryup->from('messages');
$queryup->where("id = $id");
$querydown->select('down');
$querydown->from('messages');
$querydown->where("id = $id");
$db->setQuery( $query );
$db->query();
$db->setQuery( $query2 );
$db->query();
$db->setQuery( $queryup );
$data0 = $db->query();
$db->setQuery( $querydown );
$data1 = $db->query();
$up_value= $db->insertid($data0);;
$down_value = $db->insertid($data1);
$total=$up_value+$down_value;
$up_per=($up_value*100)/$total;
$down_per=($down_value*100)/$total;
?>
<table width="700px">
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $up_value; ?></td>
<td width="600px"><div id="greebar" style="width:<?php echo $up_per; ?>%"></div></td>
</tr>
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $down_value; ?></td>
<td width="600px"><div id="redbar" style="width:<?php echo $down_per; ?>%"></div></td>
</tr>
</table>
<?php
}
Try this
$query->where('id = ' . $db->qn($id));
etc

Resources