Loading data when button is clicked using vue js and laravel - 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.

Related

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}
})

Return Action Button Shaped Text Datatable Laravel

I want to add action button to my datatable here the code
html table and datatables
<table id="users-table" class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>alamat</th>
<th>nohp</th>
<th>action</th>
</tr>
</thead>
</table>
<script id="script">
$(function () {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: 'test/json'
});
});
</script>
heres the laravel json datatables
public function data(Datatables $datatables)
{
$builder = Kontak::query()->select('id', 'nama', 'email', 'alamat', 'nohp');
return $datatables->eloquent($builder)
->addColumn('action', 'users.datatables.intro')
->rawColumns(['action'])
->make();
}
but it keeps show result like this
result images
You should try ->escapeColumns([]) before ->addColumn('action', 'users.datatables.intro')
You can use the routes methods for your model.
view :
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>alamat</th>
<th>nohp</th>
<th>action</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->alamat }}</td>
<td>{{ $user->nohp }}</td>
<td>
<form action="{{ route('users.destroy' , ['id' => $user->id]) }}" method="post">
{{ method_field('delete') }}
{{ csrf_field() }}
<div class="btn-group btn-group-xs">
edit
<button type="submit" id="deleteButton" data-name="{{ $user->id }}" class="btn btn-xs btn-warning">delete</button>
</div>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
controller:
public function index()
{
$users = User::latest()->paginate(25);
return view('users.all' , compact('users'));
}
change users.all to your users view.

[Vue warn]: Error in render: "TypeError: this.input.reduce is not a function" in Vue.js

i'm creating a very simple sum of Table of Amount by using computed in vuejs, but there is an issue come up
[Vue warn]: Error in render: "TypeError: this.input.reduce is not a function"
Still, i cant figure it out with my code.
// My Vue js
<pre>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Current_id</th>
<th>Date</th>
<th>Description</th>
<th>Amount</th>
<th colspan="2">Modify</th>
</tr>
</thead>
<tbody>
<tr v-for="(user,key) in users">
<td>{{ user.user.name }}</td>
<td>{{ user.date }}</td>
<td>{{ user.description }}</td>
<td>${{ user.amount }}</td>
<td #click.prevent="editUser(key)">
<span class="btn btn-info">Edit</span>
</td>
<td #click.prevent="remove(user.id)">
<span class="btn btn-danger">Delete</span>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<p>Total of Amount {{ total }}</p>
</div>
</pre>
// My Script file
<pre>
data() {
return {
users: [],
input: {
date: "",
description: "",
amount: ""
},
edit: false,
add: true,
}
},
computed: {
total() {
return this.input.reduce((total, item) => {
return total + item.amount;
}, 0);
}
},
</pre>
Any Help? Thanks...

How to display data returned from ajax response as a view in laravel

I'm new to Ajax, and want to return a partial view in laravel in response of an ajax call, so when I click on a link to display the data in a modal it does not work and saying trying to get property of non object. any help?
This is my code:
<tr>
<td style="border-right: 1px solid #ddd;"><?php echo $i;?></td>
<td>{{ $sale->item_name }}</td>
<td>{{ $sale->brand_name }}</td>
<td>{{ $sale->category_name }}</td>
<td>{{ $sale->fname }} {{ $sale->lname }}</td>
<td>{{ $sale->sale_date }}</td>
<td>{{ $sale->quantity }}</td>
<td>{{ $sale->unit_name }}</td>
<td><span>$</span>{{ $sale->unit_price }} </td>
<td><span>$</span><?php echo $sale->quantity*$sale->unit_price;?> </td>
<td>
<a href="#bill" class="btn btn-xs btn-green mr-5" type="button" tabindex="0" data-toggle="modal" data-target="#reportModal" onclick="load_modal_data('{{ $sale->sale_id }}','/sales/bill','billContent')">
<i class="fa fa-pencil"> Bill</i></a>
<i class="fa fa-search"> View</i>
<i class="fa fa-remove"> Del</i>
</td>
</tr>
The JS and Ajax
function load_modal_data(identity, route,target_tag)
{
$.ajax({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') },
url: route,
type:'post',
data:{ id: identity},
success:function(result){
console.log(result)
$('#'+target_tag).html(result);
}
})
}
The Controller:
public function bill()
{
$id = Input::get('identity');
$sales = DB::table('sales')
->join('brands','brands.bid','=','sales.brand_id')
->join('units','units.unit_id','=','sales.unit_id')
->join('categories','categories.cat_id', '=','sales.category_id')
->join('customers','customers.cid','=','sales.c_id')
->select('sales.*','brands.brand_name','categories.category_name','customers.fname','customers.lname','units.unit_name')
->where('sales.sale_id',$id)->first();
$returnHTML = view('partials.item-bill')->with('sales',$sales)->render();
return response()->json(array('success'=>true, 'html'=>$returnHTML));
}
This is my item-bill.blade.php
<!-- tile body -->
<div class="tile-body p-0">
<div class="table-responsive">
<table class="table mb-0" id="usersList">
<thead>
<tr>
<th style="width:20px;">No</th>
<th>Item Name</th>
<th>Company</th>
<th>Category</th>
<th>Customer</th>
<th>Sale Date</th>
<th>Quantity</th>
<th>Unit</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ $sales->item_name }}</td>
<td>{{ $sales->brand_name }}</td>
<td>{{ $sales->category_name }}</td>
<td>{{ $sales->fname }} {{ $sales->lname }}</td>
<td>{{ $sales->sale_date }}</td>
<td>{{ $sales->quantity }}</td>
<td>{{ $sales->unit_name }}</td>
<td><span>$</span>{{ $sales->unit_price }} </td>
<td><span>$</span><?php echo $sales->quantity*$sales->unit_price;?> </td>
</tr>
</tbody>
</table>
</div>
Note: I'm using Laravel 5.2
Only thing you need to change is here:
$('#'+target_tag).html(result.html);
You get an json as a response with result.html;
Finally I solved the issue and want to share here.
I did the following steps:
changing the route method from GET to POST
Route::post('sales/bill/{id}','SalesController#bill');
changing the parameters of js function load_modal_data()
<a href="#bill" ... onclick="load_modal_data('/sales/bill/{{ $sale->sale_id }}','billContent')">
changing the above function in js file as well:
function load_modal_data(route,target_tag)
{
var identity = route.substring(route.lastIndexOf('/') + 1);
// $('#'+target_tag).addClass('animation-loading')
$.ajax({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') },
url: route,
type:'post',
data:{ id: identity},
success:function(result){
$('#'+target_tag).html(result.html);
},
error: function (result) {
alert('Ooops something went wrong!');
}
});
}
And the controller as well,
public function bill($id)
{
.
.
.
}
Now it's working.

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