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

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?

Related

How to get my link to display as a link from my laravel controller

I'm trying to send an error message with a link. The issue I'm having is that when I get the error I get the html version of my link
EG: Please go to product
What I would like is for my error message to say Please go to product where as product would be a link.
Here is my code
public function updateProduct(Product $product)
{
if(!empty($product->status))
{
$url = "Product";
return redirect()->route('product.index', [$product])->with('error', "Go to $url.");
}
}
and in my index.blade.php
I have this
#section('content')
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<table class="table">
#foreach($products as $product)
<tr>
<td>
{{ $product->name }}
</td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
</div>
#endsection
#push('js')
<script type="text/javascript">
#if(session('error'))
Swal.fire('Error!', '{{ session('error') }}', 'error');
#endif
</script>
#endpush
you are sending html as response. you have to use {!! !!} to print that response as your expectation.
#push('js')
<script type="text/javascript">
#if (session('error'))
Swal.fire('Error!', '{!! session('error') !!}', 'error');
#endif
</script>
#endpush
this will show the swal as Go to Product

Fill table depending dropdown list selected value in Laravel vuejs Axios

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

Why the query from controller not display in table using ajax in Laravel?

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){
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?
I guess you should remove form action and method. Because if you are submitting form via ajax you dont need action and method. Due to action and method your form is submitting like normal post of form data and that`s why you are receiving output on browser.
{!! Form::open() !!}
{{ csrf_field() }}
//Form for filter here...
{{ Form::submit('Cari', ['class' => 'btn btn-primary', 'id' =>'search']) }}
{!! Form::close() !!}
Try these changes and see if you are getting desired result. And make ajax call with post, your search-calon route is POST
<script type="text/javascript">
$('#search').on('click', function(){
$.post("{{ URL::to('search-calon') }}",function(data){
$.each(data, function(i, value){
var tr =$("<tr/>");
tr.append($("<td/>",{
text : value.name
}))
$('#calon_anugerah').append(tr);
});
})
})
</script>

Why ajax calling for search doesn't display output?

I had search field using ajax call in laravel 5. It search in Db and display output in table. When user click on the page, it should display all db query. When user type in search field it should display the output according to the search input.
This is the controller for searching:
function action(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('itemregistrations')
->where('name', 'like', '%'.$query.'%')
->paginate(10);
}
else
{
$data = DB::table('itemregistrations')
->paginate(10);
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>'.$row->seksyen_kecil.'</td>
<td>'.$row->nobadan.'</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);
}
}
This is the view blade displaying the output:
<div class="row">
<div class="form-group">
<div class="col-lg-5">
<input type="text" class="form-control" id="search" name="search"></input>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Senarai Kakitangan</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"> -->
<h3 align="center">Total Data : <span id="total_records"></span></h3>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td><strong>#</strong></td>
<td class="text-center col-lg-1"><strong>Nama</strong></td>
<td class="text-center col-lg-3"><strong>Seksyen</strong></td>
<td class="text-center col-lg3-2"><strong>No Badan</strong></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- </div> -->
<ul class="pagination pull-right">
{{ $itemregistrations->links() }}
</ul>
</div>
#endif
#if(Auth::guest())
Anda perlu log masuk.
#endif
</div>
</div>
</div>
The javascript for searching:
<script>
$(document).ready(function(){
fetch_profil_data();
function fetch_profil_data(query = '')
{
$.ajax({
url:"{{ route('live_search.action') }}",
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_profil_data(query);
});
});
</script>
The route for the search is:
Route::get('/profil/action', 'Modul\ProfilController#action')->name('live_search.action');
I couldn't find any error and console.log also doesn't produce any output..
The searching doesn't work and don't display any result.
The script link i put in app.blade.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
This is the error in log
C:\\xampp\\htdocs\\hre1m\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php(116): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))
#50 C:\\xampp\\htdocs\\hre1m\\public\\index.php(53):
Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#51 C:\\xampp\\htdocs\\hre1m\\server.php(21):
require_once('C:\\\\xampp\\\\htdocs...')
#52 {main}
"}

Import data into database and show it on html table in laravel

I want to create a view in laravel that has a function to import an excel file into the database and show it in a table inside a view.
I created a controller and it imports the excel data in database but fails to show it in view.
Please Help solve my issue.
Many Thanks in advance.
Best Regards,
Dian
I am using laravel 5.5 and maatwebsite excel
public function importFileIntoDB(Request $request){
if($request->hasFile('sample_file')){
$path = $request->file('sample_file')->getRealPath();
$data = Excel::load($path, function($reader) {})->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['name' => $value->name, 'details' => $value->details];
}
if(!empty($arr)){
\DB::table('products')->insert($arr);
dd('Insert Record successfully.');
}
}
}
return back()->with($arr);
}
this is my view
#extends('frontpage')
#section('title', 'Dashboard')
#section('content_header')
<h1>Upload File From Excel Into Database</h1>
#stop
#section('content')
<div class="panel panel-primary">
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title" style="padding:12px 0px;font-size:25px;"><strong>Test - import export csv or excel file into database example</strong></h3>
</div>
<div class="panel-body">
#if ($message = Session::get('success'))
<div class="alert alert-success" role="alert">
{{ Session::get('success') }}
</div>
#endif
#if ($message = Session::get('error'))
<div class="alert alert-danger" role="alert">
{{ Session::get('error') }}
</div>
#endif
<h3>Import File Form:</h3>
<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
<input type="file" name="import_file" />
{{ csrf_field() }}
<br/>
<button class="btn btn-primary">Import CSV or Excel File</button>
</form>
<br/>
<h3>Import File From Database:</h3>
<div style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;">
<button class="btn btn-success btn-lg">Download Excel xls</button>
<button class="btn btn-success btn-lg">Download Excel xlsx</button>
<button class="btn btn-success btn-lg">Download CSV</button>
</div>
<h3>Table Import List </h3>
<div style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;" >
print_r($arr->count());
#if(!empty($arr))
<table class="table table-striped table-hover table-reflow">
#foreach($arr as $key=>$value)
<tr>
<th ><strong> {{ $key }}: </strong></th>
<td> {{ $value }} <td>
</tr>
#endforeach
</table>
#endif
</div>
</div>
</div>
</div>
#stop
#section('css')
<link rel="stylesheet" href="/css/admin_custom.css">
#stop
#section('js')
<script> console.log('Hi! this is frontpage'); </script>
#stop
As conveyed by #gbalduzzi you need to return the data to the view as
return back()->with(['arr' => $arr]);
and access in your view as
#if(session()->has('arr'))
<table class="table table-striped table-hover table-reflow">
#php $arr = session('arr'); #endphp
#foreach($arr as $key => $value)
<tr>
<th ><strong> {{ $value['name'] }}: </strong></th>
<td>{{ $value['details'] }} <td>
</tr>
#endforeach
</table>
#endif
Docs
Change
return back()->with($arr);
with
return back()->with(['arr' => $arr]);
return back()->with('arr', $arr); // Should be equivalent
return back()->compact($arr); // Should be equivalent
The with method doesn't accept only a single value: you need to specify an array, a key and a value or use the compact method

Resources