laravel datatable using ajax post method - laravel

How to call the jquery datatable using Ajax post method
same as this link but in post method
public function getAdvanceFilterData(Request $request)
{
$users = User::select([
DB::raw("CONCAT(users.id,'-',users.id) as id"),
'users.name',
'users.email',
DB::raw('count(posts.user_id) AS count'),
'users.created_at',
'users.updated_at'
])->leftJoin('posts', 'posts.user_id', '=', 'users.id')
->groupBy('users.id');
$datatables = app('datatables')->of($users)
->filterColumn('users.id', 'whereRaw', "CONCAT(users.id,'-',users.id) like ? ", ["$1"]);
// having count search
if ($post = $datatables->request->get('post')) {
$datatables->having('count', $datatables->request->get('operator'), $post);
}
// additional users.name search
if ($name = $datatables->request->get('name')) {
$datatables->where('users.name', 'like', "$name%");
}
return $datatables->make(true);
}

When you initialize the DataTable on javascript, set the ajax method to post like this:
"type": "POST"
(adding it on the example that you linked):
ajax: {
url: 'http://datatables.yajrabox.com/eloquent/advance-filter-data',
type: "POST",
data: function (d) {
d.name = $('input[name=name]').val();
d.operator = $('select[name=operator]').val();
d.post = $('input[name=post]').val();
}
},
and then on laravel you should be able to access the inputs in form of
$datatables->request->post('post')

Related

problem with filter data using ajax in laravel 8

I want to filter the data in my table. I want if I select the first box it will show the data accordingly and if I select the second box it will show the data accordingly but the problem is that if I select the first box here the data does not show then the second box has to be selected.
Here is my controller code
public function UpazilaWiseReportShow(Request $request){
$data = [];
$data['report_data'] = Report::distric()->status(1)
->where('upazila_id',$request->upazila_id)->where('fiscal_year', $request->fiscal_year)
->get();
return view('adc.reports.upazilla-wise-data', $data);
}
here is my view code
<script>
$(document).ready(function() {
$('#upazila_id').on('change', function() {
getFilterData();
});
$('#fiscal_year').on('change', function (e) {
getFilterData();
});
});
function getFilterData() {
$.ajax({
type: "GET",
data: {
upazila_id: $("[name=upazila_id]").val(),
fiscal_year: $("[name=fiscal_year]").val()
},
url: "{{url('adc/upazila-wise-report')}}",
success:function(data) {
$("#report_data_table").html(data);
}
});
}
</script>
You should check if your $request has your needed fields. So you have to check if your request has these fields. You can use when method for it.
With the code below, you can either select fiscal year or upazila_id or both.
$data['report_data'] = Report::distric()
->status(1)
->when(
isset($request->upazila_id),
function ($query) use ($request) {
$query->where('upazila_id', $request->upazila_id);
}
)
->when(
isset($request->fiscal_year),
function ($query) use ($request) {
$query->where('fiscal_year', $request->fiscal_year);
}
)
->get();

How to search with select 2 in laravel and ajax?

I'm trying to load into Select2 the selected value extracted from the DB. Id values are saved in a JSON field that contains the id values or the field '*' that I manage as 'All'.
I want to search first_name and last_name in users table.
AJAX
<script>
$(document).ready(function() {
$('#plaintiffId').select2({
ajax: {
url: '{{ route('admin::reports.plaintiffId') }}',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
first_name: item.user.first_name,
last_name: item.user.last_name,
}
})
};
},
cache: true
}
});
</script>
web.php
Route::get('reports/plaintiffId', 'Admin\ReportController#plaintiffId')->name('reports.plaintiffId');
Controller
public function plaintiffId(Request $request, $term)
{
$data = [];
if($request->has('q')){
$search = $request->q;
$data = $search->when($term, function ($query) use ($term){
return $query->whereHas('plaintiff', function ($query) use ($term) {
$query->where('first_name', 'like', "%{$term}%");
$query->orWhere('last_name', 'like', "%{$term}%");
});
});
}
return response()->json($data);
}
Model
public function scopeSearch($query, $term)
{
return $query->when($term, function ($query) use ($term){
return $query->whereHas('plaintiff', function ($query) use ($term) {
$query->where('first_name', 'like', "%{$term}%");
$query->orWhere('last_name', 'like', "%{$term}%");
});
});
}
public function plaintiff()
{
return $this->belongsTo(User::class, 'plaintiffId');
}
I get this error in network
You have $term parameter in your controller but you dont send any parameter to your controller, you should send term parameter by ajax to your controller

The data from input dropdown select2 is not fetch into datatables

I did a multiselect input dropdown using select2. However, I dont really sure how to fetch the data that I call from database in the dropdown so that I can view it in datatable. Here are my codes:
Script for input dropdown select2:
$('.ethnicity').select2({
placeholder: 'Select..',
ajax: {
url: '/select2-autocomplete-ajax_ethnicity',
dataType: 'json',
delay: 250,
processResults: function ($ethnicity) {
return {
results: $.map($ethnicity, function (item) {
return {
text: item.Bangsa_updated,
id: item.id,
}
})
};
Controller for input dropdown so it will select the input typed:
public function ethnicity(Request $request)
{
$ethnicity = [];
if($request->has('q')){
$search = $request->q;
$ethnicity = DB::table("user")
->select("id","ethnic")
->where('ethnic','LIKE',"%$search%")
->get();
}
return response()->json($ethnicity);
}
The above code only to select the data from database without fetch data to datatable.
The controller below to catch data into datatable (I used this for simple dropdown, however dont know how to change so it is useful for above input dropdown.
public function fnFilter(Request $request)
{
if(request()->ajax())
{
if(!empty($request->dataGender))
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln')
->where('ethnic', $request->ethnicity)
->get();
}
else
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln', 'Umur', 'Phone', 'Dob','St', 'Country','Zip','Ct','Jantina')
->get();
}
return datatables()->of($data)->make(true);
}
$dataName = DB::table('modified_dpprs')
->select('ethnic','Jantina')
->groupBy('ethnic')
->orderBy('ethnic', 'ASC')
->get();
return response()->json($dataName);
Blade is:
<select id="ethnicity" class=" ethnicity form-control select2-allow-clear" style="width:200px;" name="namaDUN" multiple >
<option value="">Select</option>
My idea is to put the result from controller function ethnicity into function fnFilters. But I dont know how can do it.
you can return response in select2 (controller function) required format
like
$final_array = [];
$ethnicity = DB::table("user")
->select("id","ethnic");
if ($request->search != '') {
$search = $request->search ;
$ethnicity=$ethnicity->where('ethnic','LIKE',"%$search%");
}
// loop the results to make response
foreach($ethnicity->get() as $key => $value):
$final_array[$key]['id'] = $value->id;
$final_array[$key]['text'] = $value->ethnic;
endforeach;
return ['results' => $final_array];
// function ends here
and select 2 tag in blade file like this
$('.ethnicity').select2({
placeholder: 'Select..',
ajax: {
url: '/select2-autocomplete-ajax_ethnicity',
minimumInputLength: 3,
data: function (params) {
var query = {
search: params.term,
page: params.page || 1
}
return query;
}
}
});

Laravel How I can return view data with respone json (both in 1 time)?

public function index(Request $request)
{
$search_book = $request->id;
$proc=DB::select(DB::raw("SELECT * FROM BOOKS WHERE BOOKID = '$Search_book'")
if ($search_book!="") {
return response()->json($proc);
return view('status.status',[
'proc' => $proc
]);
}
How to return 2 data
To determine if a request is an ajax request, you can use the ajax() method on a Request object injected into the controll action:
public function index(Request $request)
{
$results = DB::table('books')
->where('bookid', $request->id)
->get();
if ($request->ajax()) {
return response()->json($results);
}
return view('status.status', [
'proc' => $results
]);
}
I went ahead and fixed the SQL injection vulnerability in your query for you by swapping the query for a proper one. It could still be improved by using a Book model instead of a plain database query, but it is fine this way as well.
The query from your comment can be simplified by replacing the left join. Simply take the sub query as base and right join it with processspj:
DB::table('processtrans as pt')
->leftJoin('processmaster as pm', 'pm.pcm_id', '=', 'pt.pct_pcm_id')
->rightJoin('processspj as ps', 'ps.pc_id', '=', 'pt.pct_pc_id')
->where('pt.pct_pc_id', $request->id)
->select([
'ps.*',
'pm.pcm_bname',
'pt.created_at',
'pt.updated_at',
'pt.pct_id',
'pt.pct_leadtime',
'pt.pct_pcm_id',
'pt.pct_pc_id',
'pt.pct_planfinishdate',
'pt.pct_startdate',
'pt.pct_status',
])
->get();
$(document).ready(function(){
$("#dl_books").change(function()
{
var getValue=$(this).val();
$.ajax({
type: 'GET',
url: '{{route('status')}}',
data: {id:getValue},
success:function(data)
{
//Json for value textbox
$("#txtbookname").text(data[0].pcm_bname);
}
});
});
});
Just save the rendered view in a variable and do a json response:
public function index(Request $request) {
$results = DB::table('books')
->where('bookid', $request->id)
->get();
if ($results) {
$view = view('status.status', [
'proc' => $results
])->render();
return response()->json(['view'=> $view, 'proc' => '$results']);
}
}

Ajax changing the entire sql query

http://rimi-classified.com/ad-list/west-bengal/kolkata/electronics-and-technology
The above link has a filter in the left. I am trying to use ajax to get city from state. but as the ajax is triggered the entire query is changing.
SELECT * FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'pages'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
It is taking the controller name in the query (controller name is pages).
The actual query is:
SELECT *
FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'electronics-and-technology'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
// Controller
public function ad_list($state,$city,$category,$sub_cat=FALSE)
{
if($state===NULL || $city===NULL || $category===NULL)
{
redirect(base_url());
}
$data['ad_list'] = $this->home_model->get_adlist($state,$city,$category,$sub_cat);
$this->load->view('templates/header1', $data);
$this->load->view('templates/search', $data);
$this->load->view('ad-list', $data);
$this->load->view('templates/footer', $data);
}
public function get_cities()
{
$state_id = $this->input->post('state');
echo $this->city_model->get_cities($state_id);
}
// Model
public function get_adlist($state,$city,$category,$sub_cat=FALSE)
{
if ($sub_cat === FALSE)
{
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
}
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('sub_cat_slug', $sub_cat);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
return $query->result_array();
//echo $this->db->last_query();
}
//ajax
<script type="text/javascript">
$(document).ready(function () {
$('#state_id').change(function () {
var selState = $(this).val();
alert(selState);
console.log(selState);
$.ajax({
url: "pages/get_cities",
async: false,
type: "POST",
data : "state="+selState,
dataType: "html",
success: function(data) {
$('#city').html(data);
$("#location_id").html("<option value=''>--Select location--</option>");
}
})
});
});
</script>
Please help me how to solve this issue. Please check the url I have provided and try to select a state from the filter section the problem will be more clear.
In .js what is the value of selState ?
In your model, you should if() else() instead of just a if, because your query will get override.
Where is the get_cities function ? Can we see it ?
On your url, the problem is that your ajax url doesn't return a real ajax call but an entire HTML page which is "harder" to work with. Try to change it into json (for dataType's ajax()) You should only do in your php something like this :
in your controller :
public function get_cities()
{
$state = $this->input->post('state');
//Do the same for $cat
if (!$state) {
echo json_encode(array('error' => 'no state selected'));
return 0;
}
$get_cities = $this->model_something->getCitiesByStateName($state);
echo json_encode($get_cities);
}
You should definitely send with ajax the $cat info

Resources