Fill table depending dropdown list selected value in Laravel vuejs Axios - laravel

I am trying to get data in the table code are as below
I want to autofill the table with the depending dropdownlist selected value. i’ve been finding solution since days but didn’t get any success. I’m very new at this.
If anyone could help to get me out from this issue i’ll be very grateful. Thank You.
Here Is my HTML code
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">employees Table</h3>
<div class="card-body">
<div class="md-3">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<select
name="company_id"
id="company_id"
:class="{'is-invalid':form.errors.has('company_id')}"
class="form-control"
v-model="form.company_id"
#change="getEmployeesbyCompany()"
>
<option value selected>Select Company</option>
<option
v-for="Company in Companies.data"
:key="Company.id"
>{{Company.Company}}</option>
</select>
<has-error :form="form" field="company_id"></has-error>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<div class="col-md-12"></div>
<table class="table table-hover">
<!-- <thead>
</thead>-->
<tbody>
<tr>
<th>ID</th>
<th>Badge#</th>
<th>Company</th>
<th>BadgeType</th>
<th>Nationality</th>
<th>Last Name</th>
<th>First Name</th>
<th>Telphonenumber</th>
<th>Position</th>
<th>SupervisorName</th>
<th>SupervisorNumber</th>
<th>Issuedate</th>
<th>Tazker</th>
<th>Expiredate</th>
<th>Serialnumber</th>
<th>Modify</th>
</tr>
<tr v-for="employee in employees.data" :key="employee.id">
<td>{{employee.id}}</td>
<td>{{employee.BadgeCode|UppCaseFirstLetter}}</td>
<!-- <td>{{employee.company_id}}</td> -->
<td>{{Company.Company}}</td>
<td>
<span class="tag tag-success">{{employee.BadgeType}}</span>
</td>
<td>{{Nationality.nationality}}</td>
<td>{{employee.lastname |UppCaseFirstLetter}}</td>
<td>{{employee.firstname |UppCaseFirstLetter}}</td>
<td>{{employee.telphonenumber |UppCaseFirstLetter}}</td>
<td>{{employee.position |UppCaseFirstLetter}}</td>
<td>{{employee.supervisorname |UppCaseFirstLetter}}</td>
<td>{{employee.supervisornumber|UppCaseFirstLetter}}</td>
<td>{{employee.Issuedate|mydate}}</td>
<td>{{employee.tazker|UppCaseFirstLetter}}</td>
<td>{{employee.Expiredate |mydate}}</td>
<td>{{employee.serialnumber |UppCaseFirstLetter}}</td>
</tr>
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer">
<pagination :data="employees" #pagination-change-page="getResults"></pagination>
</div>
</div>
<!-- /.card -->
</div>
My #change="getEmployeesbyCompany" method:
methods: {
getEmployeesbyCompany: function() {
axios.get("api/getEmployees", {
params: {company_id: this.form.company_id}})
.then( function(response) {this.employees = response.data;}.bind(this)
);
}
Route:
Route::get('getEmployees','API\EmployeeController#getEmployees');
My getEmployees(){} method:
public function getEmployees(Request $request)
{
$employees = Employee::where('company_id',$request->company_id)->get();
return $employees;
}
My data() in Vue Component:
data() {
return {
editMode: false,
selectedTicketInvoiceId: false,
Companies: {},
Nationalities: {},
employees: {},
form: new Form({id: "",BadgeCode: "",BadgeType: "",company_id: "",
nationality_id: "",lastname: "",firstname: "",telphonenumber: "",
position: "",supervisorname: "", supervisornumber: "",
issuedate: "",tazker: "", expiredate: "", serialnumber: "" })};
}

The issue is that your table is using employees.data in the v-for directive. This works fine on the initial page load, because employees is a Laravel paginator, so the data property is defined, and it contains the array of employees, as expected.
However, your controller function is simply returning an array of employees. You are saving that array to your Vue instance's employees property. So now employees.data is undefined, and your table is empty.
To fix the issue, you can update your controller function like this:
public function getEmployees(Request $request)
{
$employees = Employee::where('company_id',$request->company_id)->get();
return ['data' => $employees]; // or return response()->json(['data' => employees]);
}

Related

Select Option fetch data to label using ajax in laravel

I tried fetching the data after selecting an accountnumber using ajax it did work but after selecting once I can't select again. I've been trying some solutions but it didn't work.
AccountController.php
public function index()
{
$AM= new AM();
$AM->setConnection('AM');
$key= '';
$getData = $AM->where('Accountnumber',Auth::user()->AccountNum)->get();
foreach($getData as $row){
$key= $row->key;
}
$getAMData = $AM->where('key',$key)
->select('Accountnumber')
->get();
$ci= $AM->where('Accountnumber',Auth::user()->AccountNum)
->select('Accountnumber', 'cn', 'ca','ct','accountstatus')
->get();
return view('account')->with('getAMData',$getAMData)->with('ci',$ci);
}
// Methods
public function fetch(Request $request){
if($request->ajax())
{
$AM= new AM();
$AM->setConnection('AM');
$getData = $AM->where('Accountnumber',$request->Accountnumber)->get();
foreach($getData as $row){
$key= $row->key;
}
$getAMData = $AM->where('key',$key)
->select('Accountnumber')
->get();
$ci= $AccountMaster->where('Accountnumber',$request->Accountnumber)
->select('Accountnumber', 'cn', 'ca','ct','accountstatus')
->get();
return view('partials._fetch')->with('getAMData',$getAMData)->with('ci',$ci);
}
}
ajax.js
$(document).ready(function(){
$('#accountnum').change(function(){
var Accountnumber = $(this).val();
$.ajax({
url:"/fetch",
method: "GET",
data: {Accountnumber:Accountnumber},
success:function(data){
$('#showbill').html(data);
}
});
});
});
account.blade.php
<div class="container-fluid col-sm-12">
<h3><b> Account </b></h3>
</div>
</div>
<div class="container-fluid py-4 col-sm-12" id="showbill">
#include('partials._fetch')
</div>
I think my problem would be on my controller, maybe the fetch method is not right. anyone can help me with this? Thank you!
_fetch.blade.php
<div class="row">
<div class="col-md-3 col-sm-12">
#if(count($getAMData) > 0)
<select class="form-control form-control-md" id="accountnum" name="accountnum">
<option value="" selected></option>
#foreach($getAMData as $row)
<option value="{{ $row->Accountnumber }}">{{ $row->Accountnumber }}</option>
#endforeach
</select>
#else
<p></p>
#endif
</div>
<div class="col-md-12 col-sm-12 py-4">
<div class="card">
<div class="card-body">
#if(count($ci) > 0 )
#foreach ($ci as $row )
<div class="col-md-6 col-sm-12">
<label>Account Number:</label> <label><strong>{{ $row->Accountnumber }}</strong></label>
</div>
<div class="col-md-6 col-sm-12">
<label>Name:</label> <label><strong>{{ $row->cn}}</strong></label>
</div>
<div class="col-md-6 col-sm-12">
<label> Address:</label> <label><strong>{{ $row->ca}}</strong></label>
</div>
<div class="col-md-6 col-sm-12">
<label>Type:</label> <label><strong>{{ $row->ct}}</strong></label>
</div>
<div class="col-md-6 col-sm-12">
<label>Account Status:</label> <label><strong>{{ $row->ct}}</strong></label>
</div>
#endforeach
#else
<p>NO DATA FOUND</p>
#endif
</div>
</div>
</div>
<div class="col-md-12 col-sm-12">
<table class="table table-responsive-md table-hover ">
<thead style="text-align: center;" class="bg-warning ">
<tr>
<th scope="col">(MW)</th>
<th scope="col">Morning (0001H to 1200H)</th>
<th scope="col">Afternoon (1201H to 1800)</th>
<th scope="col">Evening (1801 to 2400)</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row"></th>
</tr>
</tbody>
</table>
</div>
</div>
I tried using the same concept with the paginate using ajax well it didn't turn out to be what I expected haha
Okay so here is my solution to this problem. Instead of including the Select Option I put it inside my account.blade.php so that it wont regenerate two select options.

Laravel vuejs 'Cannot read property of data' error

Been trying to figure this out for half an hour now and I cant seem to fix the error, here is my vue component:
<template>
<div class="container">
<div class="row mt-5">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Country Lists</h3>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover">
<tr>
<th>Year</th>
</tr>
<tr v-for="country in countries.data" :key="country.id">
<td>{{country.name}}</td>
</tr>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</div>
</div>
</template>
<script type="text/javascript" src="node_modules/vuejs/dist/vue.min.js"></script>
<script type="text/javascript" src="node_modules/vue-simple-search-dropdown/dist/vue-simple-search-dropdown.min.js"></script>
<script>
export default {
data(){
return{
country : {},
form: new Form({
id : '',
})
}
},
methods: {
loadCountry(){
axios.get('api/country').then(({data}) => (this.countries = data));
}
},
mounted() {
this.loadCountry();
Fire.$on('reloadAfter',() => {
this.loadCountry();
});
}
}
</script>
When I load the page the table wont display, but when I check the network from the developer tab in chrome, it can and loads the data, however it displays this error in the console 'Cannot read property 'data' of undefined'.
Thanks in advance.
The problem is here
<tr v-for="country in countries.data" :key="country.id">
<td>{{country.name}}</td>
</tr>
countries is not defined yet.
You can, for example, add it to data()
data(){
return{
countries : {},
},
}
And test the presence of data
<table v-if="countries.data" class="table table-hover">

Why output using ajax not display in table but json format?

I want to create a searching filters and display the output using ajax.
This is the button for submit the data:
{!! Form::open(['method' => 'POST', 'action' => 'Modul\CarianAnugerahController#search']) !!}
//Form for filter here...
{{ Form::submit('Cari', ['class' => 'btn btn-primary', 'id' =>'search']) }}
{!! Form::close() !!}
This is the output table under the form:
<div class="panel panel-default">
<div class="panel-heading">Senarai Calon Anugerah</div>
<div class="panel-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
#if(Auth::check())
<div class="container table-responsive col-lg-12">
<!-- <div class="container text-center"> -->
<table class="table table-striped table-bordered" id="calon_table" >
<thead>
<tr>
<td class="text-center col-lg-3"><strong>Name</strong></td>
<td class="text-center"><strong>Action</strong></td>
<!-- <td class="text-center"><strong>Lihat Rekod</strong></td> -->
</tr>
</thead>
<tbody id="calon_anugerah">
</tbody>
</table>
<!-- </div> -->
</div>
#endif
#if(Auth::guest())
Anda perlu log masuk.
#endif
</div>
</div>
</div>
The ajax code to get the data is:
<script type="text/javascript">
$('#search').on('click', function(){
$.get("{{ URL::to('search-calon') }}",function(data){
$.each(data, function(i, value){
// alert(value.name);
var tr =$("<tr/>");
tr.append($("<td/>",{
text : value.name
}))
$('#calon_anugerah').append(tr);
});
})
})
</script>
I had queried the data using the code in CarianAnugerahController#search:
$query = DB::table('itemregistrations')
->select('itemregistrations.ItemRegistrationID','itemregistrations.name', 'itemregistrations.Nobadan');
if(request('umur')) {
$query->whereRaw('YEAR(CURDATE()) - lahir_yy >= ?', [request('umur')]);
}
if(request('negeri_lahir')) {
$query->where('NegeriID', request('negeri_lahir'));
}
if(request('kategori')) {
$query->where('CategoryID', request('kategori'));
}
if(request('pangkat')) {
$query->where('OperasiID', request('pangkat'));
}
$newitem = $query->get();
return response($newitem);
This is the route:
Route::resource('carian_anugerah', 'Modul\CarianAnugerahController');
Route::post('/search-calon', 'Modul\CarianAnugerahController#search');
I can get the value but it doesn't display in table..it shows the output in json format in a white page..
example output..in browser.
What is missing in the ajax code?

Fetch Records in Angular datatable

Im new to Angular and My Requirement is
A component includes a form with the field name call "Brand" and a button to add the same record to database through angular service and there should be a datatable which is fetching all brand data from database to data table.
so by using fetchall method in ts file, i am assigning values to data table. im calling fetchall method to ngoninit() which helps me to show the data in table while component get initialized. to add record, i am using a method call addyear() and calling the same method to onSumbit(). my problem is when i add the record to database, i should be able to load newly added record to angular data table! since that method in ngoninit(), i have to refresh the browser to get the record in data table kindly give me a solution. for the back end, im using Spring boot with Postgres database
My Component TS file
constructor(private brandService:BrandService,private toastyService: ToastyService) { }
ngOnInit() {
this.findbrand();
}
onSubmit()
{
this.saveBrand();
this.submitted=true;
}
saveBrand()
{
this.brandService.addbrand(this.brand).subscribe
(data=>this.addToast({title:'Record Has been added Successfully', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'success'}),
error=>this.addToast({title:'Record Not Added! Sorry', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'error'}));
this.brand=new Brand();
}
findbrand()
{
this.brandService.findbrand().subscribe(data=>this.data=data,error=>this.addToast({title:'Record Cannot be found! Sorry', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'error'}));
}
My Service.TS file
export class BrandService {
constructor(private http:HttpClient) { }
private baseUrl='http://localhost:8080/snazzy-engine/brand';
addbrand(brand:object):Observable<any>
{
return this.http.post(`${this.baseUrl}` + `/insert`, brand,{
headers: {'schemaName':'test.'}
});
}
findbrand():Observable<any>
{
return this.http.get(`${this.baseUrl}` + `/find-all`,{
headers: {'schemaName':'test.'}
});
}
getbrandid(id: number): Observable<Object> {
return this.http.get(`${this.baseUrl}/find-one/${id}`, {headers:
{'schemaName':'test.'}});
}
}
My HTML File
<div class="table-content crm-table">
<div class="project-table">
<div id="crm-contact" class="dt-responsive">
<div class="row">
<div class="col-xs-12 col-sm-12 col-sm-12 col-md-6">
<div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-6">
<div style="text-align: right;">
<label>Search:
<input type="search" [(ngModel)]="filterQuery" class="form-control input-sm full-data-search" placeholder="Search name">
</label>
</div>
</div>
</div>
<!-- <div class="panel-heading">User information</div>-->
<div class="table-responsive">
<table class="table table-bordered table-hover table-sm" [mfData]="data | dataFilter : filterQuery" #mf="mfDataTable" [mfRowsOnPage]="rowsOnPage" [(mfSortBy)]="sortBy"
[(mfSortOrder)]="sortOrder">
<thead class="thead-dark text-center">
<tr>
<th style="width:10%">
<mfDefaultSorter by="brandId">Brand ID</mfDefaultSorter>
</th>
<th style="width:70%">
<mfDefaultSorter by="name">Brand Name</mfDefaultSorter>
</th>
<th style="width:10%">
<mfDefaultSorter by="more">More</mfDefaultSorter>
</th>
<th style="width:10%">
<mfDefaultSorter by="checkbox">Delete</mfDefaultSorter>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of mf.data; let i = index;">
<td>{{item.brandId}}</td>
<td>{{item.brand}}</td>
<td class="action-icon">
<button type="button" class="btn btn-sm btn-primary" (click)="findybrandid(item.brandId);modalDefault.show();">
edit
</button>
</td>
<td>
<div class="checkbox text-center">
<label><input type="checkbox" value=""></label>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="10">
<mfBootstrapPaginator class="pagination-main f-right"></mfBootstrapPaginator>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div style="text-align:center;">
<button class="btn btn-out btn-danger ripple light"><i class="icofont icofont-check-circled"></i>Delete</button>
</div>
</div>
</div>
</div>
try this
saveBrand()
{
this.brandService.addbrand(this.brand)
.subscribe(
data => this.addToast(
{
title:'Record Has been added Successfully',
msg:'',
timeout: 5000,
theme:'default',
position:'top-right',
type:'success'
}),
error => this.addToast(
{
title:'Record Not Added! Sorry',
msg:'',
timeout: 5000,
theme:'default',
position:'top-right',
type:'error'
})
);
this.data.push(this.brand); /*change: push new data into an array*/
this.brand=new Brand();
}

knockoutjs refresh or update

I trying create a ajax-refresh shopping-cart panel. My shopping-cart is listed but I can't refresh it in $.getJSON callback function. my view and code is;
<div class="panel panel-info">
<div class="panel-heading">
<i class="fa fa-list-ul"></i> Sipariş Listeniz
</div>
<div class="panel-body">
<div id="cart" data-bind="foreach: Currencies">
<div class="">
<span data-bind="text: Currency"></span>
<table class=" table table-striped" data-bind="foreach: Items">
<tr>
<td data-bind="text: Code"></td>
<td data-bind="text: Amount"></td>
<td data-bind="text: Price"></td>
<td data-bind="text: LineTotal"></td>
</tr>
</table>
</div>
</div>
</div>
<div class="panel-footer">
</div>
</div>
and
var cartViewModel = {
Currencies: ko.observableArray()
};
$(function () {
ShowCart();
});
function AddToCart(i, a) {
$.getJSON('#Url.Action("AddToCart", "Products")/' + i + '?Amount=' + a, null, function (d) {
if (d)
ShowCart();
});
}
function ShowCart() {
$.getJSON('#Url.Action("GetCart","Products")', null, function (c) {
cartViewModel.Currencies = ko.observableArray(c);
cartViewModel.Currencies.valueHasMutated();
ko.applyBindings(cartViewModel);
});
}
How can I refresh the binding in the $.getJSON callback?
I think your problem is that you're overwriting the observables in your view-model.
All you need to do is pass a new value into the existing observable.
Try this instead:
function ShowCart() {
$.getJSON('#Url.Action("GetCart","Products")', null, function (c) {
cartViewModel.Currencies(c);
});
}

Resources