change datatable data after ajax sucess ( as per Selection box) - laravel

I am new to Laravel and coding and stuck at point where i want to change to data table data (tbody) as per selection box value. The code is as below.
On Page load table shows data as per default selection. After ajax success, alert is showing the correct data
Selection box
<div class="form-inline">
<label><strong>Select Option :</strong></label>
<select id='selectoption' class="form-control" style="width: 150px">
<option value="material">By Material</option>
<option value="supplier">By Supplier</option>
</select>
</div>
Table
<table id="expensestable" class="table table-bordered table-hover" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Material / Supplier</th>
<th>From Date</th>
<th>To Date</th>
<th>Total Quantity</th>
<th>Total Amount</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($expdatabymaterial as $i )
<tr>
<td>{{$i->materialid}}</td>
<td>{{$i->material}}</td>
<td>{{ date('d-m-Y', strtotime ($startdateofmonth)) }}</td>
<td>{{ date('d-m-Y', strtotime ($enddateofmonth)) }}</td>
<td>{{$i->totalquantity}}</td>
<td>{{$i->totalamount}}</td>
<td>
<button type="button" class="deletedatabtn btn btn-primary"><i class="far fa-eye" title="View"></i></button>
</td>
</tr>
#endforeach
</tbody>
</table>
Ajax
$('#selectoption').change( function() {
var selectoption = $(this).find('option:selected').val();
var token = "{{ csrf_token() }}";
$.ajax({
type: 'post', //'POST'
url: '/changeselection',
data: { option: selectoption, _token: token, },
success: function (data) {
alert(data)
}
});
});
Controller
$startdateofmonth = new Carbon('first day of this month');
$enddateofmonth = new Carbon('last day of this month');
if ($req->get('option') == 'material')
{
$expdatabymaterial = Dairyexpense::selectraw('material, material, materialid, materialid, SUM(quantity) as "totalquantity", SUM(totalamount) as "totalamount"')
->whereBetween('expensesdate', [$startdateofmonth, $enddateofmonth])
->groupBy('material','materialid')->get();
return response([$expdatabymaterial]);
}
else
{
$expdatabysuuplier = Dairyexpense::selectraw('supplier, supplier, supplierid, supplierid, SUM(quantity) as "totalquantity", SUM(totalamount) as "totalamount"')
->whereBetween('expensesdate', [$startdateofmonth, $enddateofmonth])
->groupBy('supplier','supplierid')->get();
return response([$expdatabysuuplier]);
}
Thanks in advance for support and help.....

Related

How to make my table one of the tr always on the last row

This is code of my table, I've already marked the tr i wanted to set in the code
When I insert new data in the table using modal pop-up form, the new row will always show on the last row. I want to make the tr I wanted to fixed on the last row.
<table class="table table-hover" id="table1">
<thead>
<th></th>
<th>Receipt No.</th>
<th>Amount</th>
<th>Item</th>
<th>Label</th>
<th>Remark</th>
<th>Start Date</th>
<th>Due Date</th>
</thead>
<tbody id="gyFee">
#forelse ($gylight as $item)
#if($item->sx_ID == $light->sx_ID )
<tr>
<td></td>
<td>{{ $item->gylight_receipt }}</td>
<td>{{ $item->gylight_amount }}</td>
<td>{{ $item->gylight_number }}</td>
<td>{{ $item->gylight_label }}</td>
<td>{{ $item->gylight_remark }}</td>
<td>{{ $item->gylight_sDate }}</td>
<td>{{ $item->gylight_eDate }}</td>
</tr>
#endif
#empty
<tr>
<td><button class="btn btn-primary" data-toggle="modal" data-target="#guanyinModal">Add</button></td>
<td style="text-align:center;vertical-align:middle" colspan="7">No Infromation</td>
</tr>
#endforelse
{{--This is the one tr i want to set on the last row for this table --}}
<tr>
<td><button class="btn btn-primary" data-toggle="modal" data-target="#guanyinModal">Add</button></td>
</tr>
</tbody>
This is my script to ajax post the data and append it to my table
$('#guanyinAdd').click(function(e){
e.preventDefault();
var id = $('#sx_ID').val();
var receipt = $('#gylight_receipt').val();
var amount = $('#gylight_amount').val();
var number = $('#gylight_number').val();
var label = $('#gylight_label').val();
var remark = $('#gylight_remark').val();
var sDate = $('#gylight_sDate').val();
var eDate = $('#gylight_eDate').val();
$.ajax({
url: "<?= route('admin.guanyin.add.api') ?>",
method: 'post',
data:{
_token: "{{ csrf_token() }}",
sx_ID: id,
gylight_receipt: receipt,
gylight_amount: amount,
gylight_number: number,
gylight_label: label,
gylight_remark: remark,
gylight_sDate: sDate,
gylight_eDate: eDate
},
success: function(data){
console.log(data);
var guanyin = data.guanyin;
$('#gyFee').append('<tr>'+
'<td></td>'+
'<td>'+ guanyin.gylight_receipt +'</td>'+
'<td>'+ guanyin.gylight_amount +'</td>'+
'<td>'+ guanyin.gylight_number +'</td>'+
'<td>'+ guanyin.gylight_label +'</td>'+
'<td>'+ guanyin.gylight_remark +'</td>'+
'<td>'+ guanyin.gylight_sDate +'</td>'+
'<td>'+ guanyin.gylight_eDate +'</td>'+
'</tr>');
$('#guanyinModal').modal('hide');
$('#guanyinForm').trigger('reset');
}
});
});
You can keep your current code and just create <tfoot> - table footer, and put your fixed rows in table footer. All other rows can be appended to table body now

Laravel datatables can't create custom columns

I have two tables first one simple html with no datatables, second with datables. My purpose transform first table two datatables second. But I had two main problems Grazinimo terminas column is using laravel #if and column Veiksmai using if statemens as well how can i add those as custom columns in second table.
First table code
<table class="table table-bordered">
<thead class="bg-warning">
<th>Knygos pavadinimas</th>
<th>Miestas</th>
<th>Išdavimo data</th>
<th>Grąžinimo terminas</th>
<th>Vardas</th>
<th>Pavardė</th>
<th>Kliento nr.</th>
<th>Veiksmai</th>
</thead>
<tbody>
#foreach($paskolinimai as $p)
<input type="hidden"
value="{{ $skirtumas = \Carbon\Carbon::parse(\Carbon\Carbon::today()->toDateString())->diffInDays( \Carbon\Carbon::parse( $p->terminas),false) }}">
<tr>
<td>{{ $p->pavadinimas }}</td>
<td>{{ $p->miestas }}</td>
<td>{{ $p->isdavimo_data }}</td>
#if($p->grazinimo_data != NULL)
<td>
<strong style="color: green;">Knyga grąžinta!</strong>
</td>
#elseif($skirtumas > 0)
<td>
Liko <strong style="color: crimson;">{{ $skirtumas }}</strong> dienų.
</td>
#elseif($skirtumas < 0) <td>
<strong style="color: crimson;">Terminas praėjo!</strong>
</td>
#elseif($skirtumas = 0)
<td>
<strong style="color: crimson;">Šiandien paskutinė grąžinimo diena!</strong>
</td>
#endif
<td>{{ $p->vardas }}</td>
<td>{{ $p->pavarde }}</td>
<td>{{ $p->klientasnr }}</td>
#if($p->grazinimo_data == null)
<td><a href="{{ url('patvirtinti-grazinima-'.$p->id.'-'.$p->bookid) }}"
class="btn btn-primary">Grąžinimas</a> </td>
#else
<td>
<p class="btn btn-success">Grąžinta</p>
</td>
#endif
#endforeach
</tr>
</tbody>
</table>
Second table code
<script>
$(document).ready(function () {
var darbuotojai = $('#paskolinimai').DataTable({
processing: true,
serverSide: true,
ajax:
{
url: '{!! route('get.paskolinimai') !!}'
},
columns: [
{ data: 'pavadinimas', name: 'pavadinimas' },
{ data: 'miestas', name: 'miestas' },
{ data: 'isdavimo_data', name: 'isdavimo_data' },
{ data: 'vardas', name: 'vardas' },
{ data: 'pavarde', name: 'pavarde' },
],
'oLanguage': {
'sSearch': "Paieška:",
'sZeroRecords': "Nerasta atitinkančių įrašų",
'sLengthMenu': "Rodyti _MENU_ įrašų",
'sInfo': "Nuo _START_ iki _END_ viso _TOTAL_ įrašų",
'sProcessing': "Apdorojama...",
'sLoadingRecords': "Kraunama...",
'sInfoFiltered': " - (filtruojama iš _MAX_ įrašų)",
'oPaginate': {
'sFirst': "Pirmas",
'sLast': "Paskutinis",
'sNext': "Sekantis",
'sPrevious': "Ankstesnis"
},
},
'sDom': '<"top"lfip>rt<"bottom"p><"clear">',
});
});
</script>
<table id="paskolinimai" class="table table-bordered">
<thead class="bg-warning">
<th>Knygos pavadinimas</th>
<th>Miestas</th>
<th>Išdavimo data</th>
<th>Vardas</th>
<th>Pavardė</th>
</thead>
<tbody></tbody>
</table>
</div>
So how can i add Grazinimo terminas and veiksmai correctly to the second table
I recommend you to use this package:
https://yajrabox.com/docs/laravel-datatables/master/installation
then go to section add column:
https://yajrabox.com/docs/laravel-datatables/master/add-column
and in your code will be like that:
->addColumn('intro', function(User $user) {
if($condtion){return $result}
})

Use button inside controller

I am trying to search users in a panel with ajax. But along with that, I also want to edit the selected user.
I have created the button inside the controller to achieve this but the button isn't working.
Here is my controller code:
public function searchTeacher(Request $request){
if($request->ajax()){
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('users')->where('name', $query)->get();
}else{
$data = DB::table('users')->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->teacherId.'</td>
<td>'.$row->subject.'</td>
<td> <button href={{route(update-teacher-view), '.$row->id.'}}> Edit</button> </td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
Here is the ajax for search method-
<script>
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
console.log(query)
$.ajax({
url:"{{ route('search-teacher') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query);
});
});
Here is my html-
<section class="panel">
<table class="table table-striped">
<thead class="team-list chat-list-side info border-less-list">
<th>Teacher Name</th>
<th>Email</th>
<th>Teacher Id</th>
<th>Subject</th>
</thead>
<tbody>
</tbody>
</table>
</section>
A solution will be appreciated.
Thanks in advance.
Maybe it's a wrong string interpolation? Should be like this:
<?php
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->teacherId.'</td>
<td>'.$row->subject.'</td>
<td> <button href='.route('update-teacher-view', $row->id).'> Edit</button> </td>
</tr>
';
Also instead of echo-ing, just return the value, it will be automatically converted to JSON response:
// echo json_encode($data); // Change this line to below
return $data;
Render the blade file with the data this is the best solution.
In controller
return View::make('ajaxFilter',compact('data'))->render();
On ajaxFilter.blade.php
<section class="panel">
<table class="table table-striped">
<thead class="team-list chat-list-side info border-less-list">
<th>Teacher Name</th>
<th>Email</th>
<th>Teacher Id</th>
<th>Subject</th>
</thead>
<tbody>
#if($data->count() > 0)
#foreach($data as $row)
<tr>
<td>{{ $row->name }}</td>
<td>{{ $row->email }}</td>
<td>{{ $row->teacherId }}</td>
<td>{{ $row->subject }}</td>
<td>
Edit //button design
</td>
</tr>
#endforeach
#else
No data Found
#endif
</tbody>
</table>
</section>
On ajax response, you can append HTML data something like that
$('#div_or_section_id').html(data);

Loading data when button is clicked using vue js and laravel

I have this project that when a user clicks on a button the data should be displayed on a table. However, I am using a table as seen here http://i.stack.imgur.com/HW4rE.jpg. What I want is that when a user clicks on the add button on the enrollment form table, it should displayed on the added subjects table without the need of refreshing the page. The problem is that I am using a table and I cannot make use of the v-model to bind the values.
So here's my form.blade.php
Enrollment Form table
<table class="table table-bordered">
<tr>
<th>Section</th>
<th>Subject Code</th>
<th>Descriptive Title</th>
<th>Schedule</th>
<th>No. of Units</th>
<th>Room</th>
<th>Action</th>
</tr>
<body>
<input type="hidden" name="student_id" value="{{ $student_id }}">
#foreach($subjects as $subject)
#foreach($subject->sections as $section)
<tr>
<td>{{ $section->section_code }}</td>
<td>{{ $subject->subject_code }}</td>
<td>{{ $subject->subject_description }}</td>
<td>{{ $section->pivot->schedule }}</td>
<td>{{ $subject->units }}</td>
<td>{{ $section->pivot->room_no }}</td>
<td>
<button
v-on:click="addSubject( {{ $section->pivot->id}}, {{ $student_id}} )"
class="btn btn-xs btn-primary">Add
</button>
<button class="btn btn-xs btn-info">Edit</button>
</td>
</tr>
#endforeach
#endforeach
</body>
</table>
AddedSubjects Table
<table class="table table-bordered">
<tr>
<th>Section Code</th>
<th>Subject Code</th>
<th>Descriptive Title</th>
<th>Schedule</th>
<th>No. of Units</th>
<th>Room</th>
<th>Action</th>
</tr>
<body>
<tr v-for="reservation in reservations">
<td>#{{ reservation.section.section_code }}</td>
<td>#{{ reservation.subject.subject_code }}</td>
<td>#{{ reservation.subject.subject_description }}</td>
<td>#{{ reservation.schedule }}</td>
<td>#{{ reservation.subject.units }}</td>
<td>#{{ reservation.room_no }}</td>
<td>
<button class="btn btn-xs btn-danger">Delete</button>
</td>
</tr>
</body>
</table>
And here's my all.js
new Vue({
el: '#app-layout',
data: {
reservations: []
},
ready: function(){
this.fetchSubjects();
},
methods:{
fetchSubjects: function(){
this.$http({
url: 'http://localhost:8000/reservation',
method: 'GET'
}).then(function (reservations){
this.$set('reservations', reservations.data);
console.log('success');
}, function (response){
console.log('failed');
});
},
addSubject: function(id,student_id){
this.$http({
url: 'http://localhost:8000/reservation',
data: { sectionSubjectId: id, studentId: student_id },
method: 'POST'
}).then(function(response) {
console.log(response);
},function (response){
console.log('failed');
});
}
}
});
Can anyone suggets me on how to solve this problem, without the need of refreshing the page.

Getting undefined values when adding a table data using vue js and laravel

I have this project that when a user clicks on a button the data should be displayed on a table. However, I am using a table as seen here http://i.stack.imgur.com/HW4rE.jpg. What I want is that when a user clicks on the add button on the enrollment form table, it should displayed on the added subjects table without the need of refreshing the page. The problem is that I am using a table and I cannot make use of the v-model to bind the values.
So here's my form.blade.php
Enrollment Form table
<table class="table table-bordered">
<tr>
<th>Section</th>
<th>Subject Code</th>
<th>Descriptive Title</th>
<th>Schedule</th>
<th>No. of Units</th>
<th>Room</th>
<th>Action</th>
</tr>
<body>
<input type="hidden" name="student_id" value="{{ $student_id }}">
#foreach($subjects as $subject)
#foreach($subject->sections as $section)
<tr>
<td>{{ $section->section_code }}</td>
<td>{{ $subject->subject_code }}</td>
<td>{{ $subject->subject_description }}</td>
<td>{{ $section->pivot->schedule }}</td>
<td>{{ $subject->units }}</td>
<td>{{ $section->pivot->room_no }}</td>
<td>
<button
v-on:click="addSubject( {{ $section->pivot->id}}, {{ $student_id}} )"
class="btn btn-xs btn-primary">Add
</button>
<button class="btn btn-xs btn-info">Edit</button>
</td>
</tr>
#endforeach
#endforeach
</body>
</table>
AddedSubjects Table
<table class="table table-bordered">
<tr>
<th>Section Code</th>
<th>Subject Code</th>
<th>Descriptive Title</th>
<th>Schedule</th>
<th>No. of Units</th>
<th>Room</th>
<th>Action</th>
</tr>
<body>
<tr v-for="reservation in reservations">
<td>#{{ reservation.section.section_code }}</td>
<td>#{{ reservation.subject.subject_code }}</td>
<td>#{{ reservation.subject.subject_description }}</td>
<td>#{{ reservation.schedule }}</td>
<td>#{{ reservation.subject.units }}</td>
<td>#{{ reservation.room_no }}</td>
<td>
<button class="btn btn-xs btn-danger">Delete</button>
</td>
</tr>
</body>
</table>
And here's my all.js
new Vue({
el: '#app-layout',
data: {
reservations: []
},
ready: function(){
this.fetchSubjects();
},
methods:{
fetchSubjects: function(){
this.$http({
url: 'http://localhost:8000/reservation',
method: 'GET'
}).then(function (reservations){
this.$set('reservations', reservations.data);
console.log('success');
}, function (response){
console.log('failed');
});
},
addSubject: function(section,subject,student_id){
var self = this;
this.$http({
url: 'http://localhost:8000/reservation',
data: { sectionSubjectId: section.pivot.id, studentId: student_id },
method: 'POST'
}).then(function(response) {
self.$set('reservations', response.data);
console.log(response);
self.reservations.push(response.data);
},function (response){
console.log('failed');
});
}
}
});
Here's my ReservationController
class ReservationController extends Controller
{
public function index()
{
$student = Student::with(['sectionSubjects','sectionSubjects.section', 'sectionSubjects.subject'])->find(1);
return $student->sectionSubjects;
}
public function create($id)
{
$student_id = $id;
$subjects = Subject::with('sections')->get();
return view('reservation.form',compact('subjects','student_id'));
}
public function store(Request $request)
{
$subject = SectionSubject::findOrFail($request->sectionSubjectId);
$student = Student::with(['sectionSubjects','sectionSubjects.section', 'sectionSubjects.subject'])->findOrFail($request->studentId);
$subject->assignStudents($student);
return $student->sectionSubjects;
}
}
Can anyone suggets me on how to solve this problem, without the need of refreshing the page.
By the way I have this errors in my console.log
Error when evaluating expression "reservation.section.section_code": TypeError: Cannot read property 'section_code' of undefined
Error when evaluating expression "reservation.subject.subject_code": TypeError: Cannot read property 'subject_code' of undefined
Error when evaluating expression "reservation.subject.subject_description": TypeError: Cannot read property 'subject_description' of undefined
Error when evaluating expression "reservation.subject.units": TypeError: Cannot read property 'units' of undefined
You should use vue-devtools to inspect what data is actually inside reservations after it was fetched from the server.
Because the error message simply means that the objects in this array do not have a .subject property, which means the data you receive probably does not have the structure you assume it to have, and that is where your solutiuon will be found.
I don't know much PHP or Laravel, but it seems that your GET request gets its response form the index method, and this method seems to reply with an array of subjects, not an array of reservations (which should contain the subjects, according to your template code)

Resources