how to custom filter search in datatable laravel, - ajax

ajax
$(document).ready(function(){
tabel_sales = $('#tabel_sales').DataTable({
'bLengthChange': false,
scrollXInner: true,
dom : 'frtp',
processing : true,
serverside : true,
ajax : {
'url' : '{{ url("data/data_sales") }}',
'data' : function(data){
month = $('#month').val();
console.log(data);
data.searchByMonth = month;
}
}
})
$('#month').change(function(e){
tabel_sales.draw();
})
})
controller
$testing = $request->get('searchByMonth');
$get_po_apar = DB::table('tabel_header_po')
->where([
['kode_mitra', Auth::user()->kode_mitra],
['no_po', 'LIKE', '%TRX%'],
['created_by', $gd->kode_user]
])
->whereMonth('created_at',$testing)
->get();
if (count($get_po_apar) > 0) {
$po = '<button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-envelope"></i> ' . count($get_po_apar) . ' Po Apar</button>';
$fetch[] = $po;
} else {
$po = '<button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-envelope"></i> 0 Po Apar</button>';
$fetch[] = $po;
}
i have problem, I want to display data based on the month dropdown I chose, automatically the data that appears will change based on the dropdown
please Help me!

You can try using:
tabel_sales.columns("index column" or "column name").search("value").draw();
This link: https://datatables.net/reference/api/column().search()
May I help you!

Related

How to filter a record depending of the user connected using Laravel?

I have the next table..
The IDOP column is a key that I'm using for connect in my app instead of email... I would like to be able for filter the IDOP of each user... So the user should only be able to see the rows with
of its corresponding IDOP, how could I filter only his IDOP?
this is the function of my datatable
$('#user_contactabilidadasesor').DataTable({
processing: true,
"scrollX": true,
//serverSide: true,
ajax: {
url: "{{ route('contactabilidadasesor.index') }}",
},
columns: [
{
data: 'idop',
name: 'l.idop',
className: 'uniqueClassName'
},
{
data: 'idop_asesor',
name: 'idop_asesor',
searchable: false, render: function ( data, type, row ) {
if (data == null){ return ''; }else{return (row['idop_asesor'] + ' ' + row['ape_asesor'])};
},
className: 'uniqueClassName'
}
],
});
And this is my query
public function index(Request $request)
{
if($request->ajax())
{
$data = DB::table('tbl_lista_contactabilidad as a')
->select('a.id','a.postventaatcs_id')
->leftjoin('tbl_equipo_postventaatcs as h','h.id','=','a.postventaatc_id')
->leftjoin('users as l','l.id','=','h.asesor_id')
->select(array('a.id','l.name as idop_asesor','l.apellido as ape_asesor','l.idop'));
return DataTables::of($data)
->addColumn('action', function($data){
$button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Auditar</button>';
//$button .= ' <button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
return $button;
})
->rawColumns(['action'])
->make(true);
}
return view('contactabilidadasesor');
}
For filtering you have to use ->where('IDOP', auth()->user()->IDOP) (for single user) of ->whereIn('IDOP', [array of filtering idops]) for multiple IDOPs

how to redirect to a view from ajax on click in laravel?

so i am making an autocomplete live search in laravel & $ajax .
how do i redirect to a specific view in click ? i mean when i click one of the results it would send me to the product page , for now all it does is reload the page...but whan i click on the search button it just return to the same page and nothing changes in the URL address . thank you .
Route
Route::get('/search/{search}', 'SearchController#search');
blade.php
<div class="vcenter-this">
<form action="" method="GET" autocomplete="off" novalidate="novalidate">
#csrf
<div class="input-group ml-3" style="max-width: max-content; margin-left:
10px;">
<input type="text" class="form-control" value="<?= old('search'); ?>"
name="search" id="search" class="form-control" placeholder="Search Item">
<span class="input-group-btn">
<input id="search-btn" type="submit" value="GO!" name="submit"
class="btn btn-primary" >
<i class="fa fa-search"></i>
</span>
</div>
Controller
use Illuminate\Http\Request;
use DB;
use App\Search;
class SearchController extends MainController
{
public function search($search)
{
if (isset($_GET['submit'])) {
$search = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_STRING);
$search = trim($search);
}
if ($search) {
$products = DB::table('products as p')
->join('categories as c', 'c.id', '=', 'p.categorie_id')
->select('p.ptitle', 'p.purl', 'c.curl')
->where('p.ptitle', 'like', '%' . $search . '%')
->get()
->toJson();
if ($products) {
return $products;
}
}
}
}
Script.js
$('#search').on('input', function () {
var userSearch = $(this).val().trim();
if (userSearch.length > 0) {
$.ajax({
type: 'GET',
url: BASE_URL + 'search/' + userSearch ,
dataType: 'json',
//data: { search: userSearch },
success: function (products) {
if (products) {
var availableTags = [];
products.forEach(function (products) {
availableTags.push(products.ptitle);
});
$("#search").autocomplete({
source: availableTags,
select: function (event, ui) {
$('#search-btn').on('click',function(products) {
***what commend should i put here ? ***
***the destination url supposed to be like the line below ***
// window.location.href = BASE_URL + "shop/" + products.curl + '/' + products.purl;
});
}
});
}
}
});
}
});

Is there other way to set url using route?

i'm just starting to learn ajax laravel im just following a tutorial then it not working for me. thanks
my ajax looks like this:
$(document).ready(function(){
$('#courseTable').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{{ route('courses.index') }}}",
},
then in routes:
Route::resource('courses', 'CourseController');
then for my coursecontroller:
public function index()
{
// $courses = Course::orderBy('description','asc')->paginate(8);
if (request()->ajax()) {
return datatables()->of(Course::latest()->get())
->addColumn('action', function($data){
$button = '<button type="button" name="edit" id="'.$data->courseID.'"
class="edit btn btn-warning btn-sm">Edit</button>';
$button .= ' ';
$button .= '<button type="button" name="delete" id="'.$data->courseID.'"
class="delete btn btn-warning btn-sm">Delete</button>';
return $button;
})
->rawColumns(['action'])
->make(true);
}
return view('registrar.courses.index');
// ->with('courses', $courses)
}
this error shows up like this:
app.js:16034 GET http://odrs.test/%7B%7B%7B%20route('courses.index')%20%7D%7D%7D?draw=1&colum 404 (Not Found)
it's impossible to write a blade template in a separate javascript file.
you have probably 2 ways to do it:
join your eventListener in your blade view as a child.
transfer your JS file to your views file, change its extension to blade.php and include it in the view between script tags:
<script>
#include("my-view-js")
</script>

Attribute tag is not working in front-end side

I am trying to return an attribute tag from controller to front-end side but attribute link and class is not working.
Click here (image)
Controller Side
public function religionlist(){
$view_data = DB::select("SELECT
id,religion
FROM
hrm_religion");
$religion_data = collect($view_data);
return DataTables::of($religion_data)
->addColumn('Link', function ($religion_data) {
return
' <a href="'. url('/religion') . '/' .
Crypt::encrypt($religion_data->id) .
'/edit' .'"' .
'class="btn btn-success btn-sm block btn-flat"><i class="glyphicon glyphicon-edit-sign" id="customer-confrimed"></i> confirm</a>';
})
->editColumn('id', '{{$id}}')
->setRowId('id')
->make(true);
}
Front-end Side
$(document).ready(function() {
var table = $('#list_table').DataTable( {
"processing": true,
"serverSide": true,
"paging": true,
"ajax": "{{URL::to('/')}}/religion_list",
"columns": [
{ "data": "religion" },
{ "data": "Link", name: 'action', orderable: false, searchable: false},
],
"order": [[0, 'asc']]
});
});
Can you replace your return statement with below one?
return '<i class="glyphicon glyphicon-edit-sign" id="customer-confrimed"></i> Confirm'
Please review this below link
https://github.com/yajra/laravel-datatables/issues/1305
just add ->rawColumns(['Link']) in your code.
return DataTables::of($religion_data)
->addColumn('Link', function ($religion_data) {
return
' <a href="'. url('/religion') . '/' .
Crypt::encrypt($religion_data->id) .
'/edit' .'"' .
'class="btn btn-success btn-sm block btn-flat"><i class="glyphicon glyphicon-edit-sign" id="customer-confrimed"></i> confirm</a>';
})
->editColumn('id', '{{$id}}')
->setRowId('id')
->rawColumns(['Link'])
->make(true);

set entity attribute (selecting a radio button) with ajax in Symfony 2.5

I want to integrate Ajax in my Symfony project (Symfony 2.5 and jQuery 3). I want to update an attribute of an Entity when I select a radio button. For now, I can get the id of the row that I select. I have searched how to implement this, but I have not succeeded.
JS code:
$(document).ready(function(){
$("input:radio[name=locacion_destacada]").click(function () {
var id = $(this).parent().parent().attr('dataId');
alert(id);
$.ajax({
url: "/update-destacado",
type: "POST",
data: { id : id },
success: function (response) {
alert(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error: ' + errorThrown);
}
});
});
});
Any help is greatly appreciated.
You can do that in the controller by calling it in the url of ajax :
url : {{ path('your_route', {'id': id})}};
and in the controller function you can update your entity as you like
You need a controller action, which is called by your "update-destacado" route. Then read the ID from the request and update your entity.
I could resolve it. I followed the idea of this page (answer n°8), also keep in mind your answers. Thanks for your help.
Controller code:
public function DestacadoAction(Request $request, $id){
$em = $this->getDoctrine()->getManager();
//Encontrar la locacion que ya estaba como destacada y dejarla como destacado=false
$locacionDestacadaAntigua = $em
->getRepository('FilmsBundle:Locaciones')
->findOneBy(
array(
'destacado' => true
));
$locacionDestacadaAntigua->setDestacado(false);
$em->persist($locacionDestacadaAntigua);
$em->flush();
$em = $this->getDoctrine()->getManager();
//Dejar como destacada la nueva locacion
$locacionDestacadaNueva = $this->getDoctrine()
->getRepository('FilmsBundle:Locaciones')
->findOneBy(
array(
'idLocacion' => $id
));
$locacionDestacadaNueva->setDestacado(true);
$em->persist($locacionDestacadaNueva);
$em->flush();
return new Response("Ha seleccionado la locación \"" . $locacionDestacadaNueva->getNombreLocacion() . "\" como destacada.");
}
JS Code:
$(document).ready(function(){
$(".button").on("click", function (e) {
$.post(this.href).done(function (response) {
alert(response);
location.reload();
});
});
});
Twig code:
{% if locacion.destacado == true %}
<td align="center">
<a class="button" href="{{ path('admin_destacado_update', { 'id': locacion.idLocacion }) }}">
<button class="btn btn-default">
<i class="glyphicon glyphicon-ok"></i>
</button>
</a>
</td>
{% else %}
<td align="center">
<a class="button" href="{{ path('admin_destacado_update', { 'id': locacion.idLocacion }) }}">
<button class="btn btn-sm">
<i class="glyphicon glyphicon-remove"></i>
</button>
</a>
</td>
{% endif %}

Resources