I have added this package https://github.com/yajra/laravel-datatables into my package and i am trying to use it in my application.
This is the view
#section('content')
<table class="table table-bordered" id="users-table">
<thead>
<tr>
<th>Emp No</th>
<th>Birth Date</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Hire Date</th>
</tr>
</thead>
</table>
#stop
#push('scripts')
<script type="text/javascript">
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: 'http://localhost:8000/tasks',
columns: [
{ data: 'emp_no', name: 'emp_no' }
{ data: 'birth_date', name: 'birth_date' },
{ data: 'first_name', name: 'first_name' },
{ data: 'last_name', name: 'last_name' },
{ data: 'gender', name: 'gender' },
{ data: 'hire_date', name: 'hire_date' }
]
});
});
</script>
#endpush
#endsection
This is the route
Route::get('tasks', 'PrototypeController#getTasks')->name('datatable.tasks');
This is the controller
public function getTasks()
{
return Datatables::of(Employees::query())->make(true);
//returns json
}
This code loads the view containining the datatables.
The url http://localhost:8000/tasks returns the json in the web browser but the datatable is never rendered in my view. When i check in my view, there are no browser errors.
What could be the problem?.
Create two method, one display our view and other method that will process our datatables ajax request.
Display our view
public function viewTasks()
{
return view('Tasks.index');
}
Process our datatables ajax request
public function getTasks()
{
return Datatables::of(Employees::query())->make(true);
}
Reference Link :- Yajra Datatable
You should change in your controller. Add code below for showing data table:
public function task()
{
return view('datatables.Index');
}
Change in web.php file for add new route:
Route::get( 'employee','PrototypeController#task');
Add data table CDN and bootstrap also
<link href="https://datatables.yajrabox.com/css/app.css" rel="stylesheet">
<link href="https://datatables.yajrabox.com/css/datatables.bootstrap.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Lato:400,700,300|Open+Sans:400,600,700,800' rel='stylesheet'
type='text/css'>
Related
I'm getting an error when trying to setup a datatables with my laravel project.
DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see http://datatables.net/tn/7
This is my controller.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Transaction;
use DataTables;
use Illuminate\Support\Facades\DB;
class TestTableController extends Controller
{
public function index()
{
return view('testtable');
}
public function getTestTable(Request $request)
{
if ($request->ajax()) {
$data = DB::table('transactions')->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$actionBtn = 'Edit Delete';
return $actionBtn;
})
->rawColumns(['action'])
->make(true);
}
}
}
This my route.
Route::get('testtable', [TestTableController::class, 'index']);
Route::get('testtable/list', [TestTableController::class, 'getTestTable'])->name('testtable.list');
View/blade.
<body>
<div class="container mt-5">
<h2 class="mb-4">Laravel 7|8 Yajra Datatables Example</h2>
<table class="table table-bordered yajra-datatable">
<thead>
<tr>
<th>ID</th>
<th>Amount</th>
<th>Charge</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js">
</script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js">
</script>
<script type="text/javascript">
$(function () {
var table = $('.yajra-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('testtable.list') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'amount', name: 'amount'},
{data: 'charge', name: 'charge'},
{
data: 'action',
name: 'action',
orderable: true,
searchable: true
},
]
});
});
</script>
This is the error from laravel debugbar.
But the query did have results.
This is the output if I echo the query.
$data = DB::table('transactions')->get();
echo $data;
Anything else I'm missing? The exact same code is working if I tested in a new fresh laravel installation. This is an existing project that I try to implement datatables. I guess there must be something from current project configuration that causing the issue.
Your code in getTestTable function look fine. You got in the debugbar:
No query results for model [App\Frontend] testtable
But the code in getTestTable has nothing related to testtable so I guess route('testtable.list') doesn't get to that function. And the reason may be because you put a route like Route::get('testtable/{id}',... before Route::get('testtable/list', so when you call testtable/list, it will take list as id and go to other function.
If my guess is true, you can fix it by putting testtable/list before testtable/{id} route.
I share full details with Sample Code from my Project, this below Example code is a Manage Role DataTable from my project. please refer step by step & try to understand it.
first of all you need to install Laravel Yajra DataTable using below Composer command
composer require yajra/laravel-datatables-oracle
then after Define Routes in web.php as like my sample code
Route::get('/', [\App\Http\Controllers\Admin\RoleController::class, 'index'])->name('admin.roles.index'); //index all the data view...
Route::post('/', [\App\Http\Controllers\Admin\RoleController::class, 'getIndexUsers'])->name('admin.roles.getIndexRoles'); //Get Users for Laravel Yajra Datatable Index Page record...
then after create view file for it, I share sample from my project
<div class="card-body">
<table id="role_table" class="table table-bordered table-striped w-100">
<thead>
<tr>
<th>No.</th>
<th>Role Name</th>
<th>Role Slug</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>No.</th>
<th>Role Name</th>
<th>Role Slug</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
& in Footer Script define Function for Initialize the DataTable like below,
<script type="text/javascript">
var dataTable = $('#role_table').DataTable({
lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
processing: true,
serverSide: true,
order: [],
searchDelay: 500,
"scrollX": "auto",
"responsive": true,
// "lengthChange": false,
"autoWidth": true,
ajax: {
url: '{{ route("admin.roles.getIndexRoles")}}',
type: 'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: function (data) {
// data.fromValues = $("#filterUserType").serialize();
},
},
columns: [
{data: 'SrNo', //try with data: 'SrNo' OR data: 'id',
render: function (data, type, row, meta) {
// return meta.row + meta.settings._iDisplayStart + 1;
return meta.row + 1;
}, searchable: false, sortable: false
},
{data: 'role_name', name: 'role_name'},
{data: 'role_slug', name: 'role_slug'},
{data: 'action', name: 'action', searchable: false, sortable: false},
],
});
</script>
then after In your Controller load Yajra DataTable Class for use it
use Yajra\DataTables\DataTables; //for Laravel DataTable JS...
Now, create Function for Display View File like this,
public function index()
{
return view('admin.roles.index');
}
Now I crated Function method for Ajax Request for DataTable Initialize
public function getIndexUsers(Request $request)
{
$roles = Role::select('roles.*');
if($request->order ==null){
$roles->orderBy('id', 'desc');
}
$detail_data = $roles;
return Datatables::of($detail_data)
->addColumn('action', function ($data) {
return $this->DataTableAction($data);
})
->rawColumns(['action'])
->make(true);
}
public function DataTableAction($data){
$btn = '<div class="btn-group">';
if($data->id == "1" || $data->id == "2"){
$btn .= '<button type="button" class="btn btn-danger dropdown-toggle ml-2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" disabled>Action
</button>';
}else{
$btn .= '<button type="button" class="btn btn-danger dropdown-toggle ml-2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action
</button>';
}
$btn .= '<div class="dropdown-menu">';
$btn .= '<a class="dropdown-item" href="'.route('admin.roles.edit',$data->id).'" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-edit text-primary"></i> Edit</a>';
$btn .= '<div class="dropdown-divider"></div>';
$btn .= '<a role_id="'.$data->id.'" class="dropdown-item deleteRole" href="#" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-trash-alt text-danger"></i> Delete</a>';
$btn .= '</div>
</div>';
return $btn;
}
Important Note:- Currently I use Laravel 8 So, It's not necessary to needs to define Yajra Service Provider Class in config/app.php . But if you are getting any error in your different Laravel version then you wil needs to define Yajra Service Provider Class in config/app.php... for define it follow below steps
**
Note that, below step not compulsory, its depends on your Laravel
version
**
config/app.php
.....
'providers' => [
....
Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
....
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....
then Run below Command
php artisan optimize
then if you get any problem, try to Clear Cache using
php artisan cache:clear
Important Note:- If you define Service Provider Class in config/app.php & run optimize command, then May be Laravel will load it in autoload which is automatically called when your code references a class or interface that hasn't been loaded yet, I'm not sure
if everything is ok in the app codes,
you may loosed config for yajra..
so to configure it, you can go to the config folder in the app root directory and then open app.php file from there and add this line to the provider..
Yajra\DataTables\DataTablesServiceProvider::class
the result will be something like this:
'providers' => [
..
..
..
Yajra\DataTables\DataTablesServiceProvider::class,
]
and also add this line to the aliases:
Yajra\DataTables\Facades\DataTables::class
try like this:
'aliases' => [
..
..
..
..
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
finally, save the file(config\app.php) like above and then open up cmd or terminal and try to clear the app cached file(that includes the config cache) using the fallowing command:
php artisan optimize
I have taken an example from the internet of working laravel with ajax. But it gives me the 500 internal server error:
jquery.min.js:4 GET 127.0.0.1:8000/search?search=p 500 (Internal Server Error) send # jquery.min.js:4 ajax # jquery.min.js:4 (anonymous) # (index):39 dispatch # jquery.min.js:3 r.handle # jquery.min.js:3
This is the code for controller called SearchController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function index()
{
return view('search.search');
}
public function search(Request $request)
{
if($request->ajax())
{
$output="";
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
if($products)
{
foreach ($products as $key => $product) {
$output.='<tr>'.
'<td>'.$product->id.'</td>'.
'<td>'.$product->title.'</td>'.
'<td>'.$product->description.'</td>'.
'<td>'.$product->price.'</td>'.
'</tr>';
}
return Response($output);
}
}
}
}
Code in web.php
Route::get('/','SearchController#index');
Route::get('/search','SearchController#search');
Code of blade file
<!DOCTYPE html>
<html>
<head>
<meta id="token" name="_token" content="{{ csrf_token() }}">
<title>Live Search</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Products info </h3>
</div>
<div class="panel-body">
<div class="form-group">
<input type="text" class="form-controller" id="search" name="search"></input>
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
});
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
</body>
</html>
It should display the record when the key is pressed but it gives error 500 internal server error
Screenshot with GET method
AJAX ERROR WITH GET
Screenshot with POST method
AJAX ERROR WITH POST
Try this
<script type="text/javascript">
$('#search').on('keyup',function(){
value=$(this).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url : '{{ url('search') }}',
method : 'POST',
data:{'search': value},
success:function(response){
console.log(response.data)
}
});
})
</script>
your route
Route::post('/search','SearchController#search');
and in your controller, verify
public function search(Request $request)
{
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
return response()->json(['data' => $products]);
}
The problem is, There is no DB imported.
So Just write
use DB;
in the controller
I'm beginner in DataTables or dev in general :)
I use Laravel 5.4 and several DataTables which get their data using ajax calls requests and everything it's working just fine :) .
One of the tables have a column with a hyperlink on it I need to send further in the hyperlink an external variable which is not returned by Ajax response but it's hidden in same form with the table.
So, I have the table definition:
$('#tabelClientiOferta').DataTable({
lengthMenu: [[15, 25, 100, -1], [15,25, 100, "All"]],
processing: true,
serverSide: true,
ajax: 'ajaxClienti',
columns: [
{data:'id',name:'id' , sClass: "hidden", "bSearchable": false },
{data: 'denumire', name: 'denumire',
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='selectieFurnizor?idClient=" + oData.id + "'>" + oData.denumire + "</a>")
}
},
{ data: 'cui', name: 'cui' },
{ data: 'telefon', name: 'telefon', "bSearchable": false},
{ data: 'email', name: 'email', "bSearchable": false },
]
});
Controller function which respond to ajax call:
public function clienti(Request $request)
{
return Datatables::of(DB::table('clienti')->get(['id','denumire','cui','telefon','email']))->make(true);
}
HTML template with table and hidden variable:
#extends ('master')
#section('content')
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="tabelOferte" style ="width: 900px">
<table id = "tabelClientiOferta" class="table table-responsive table-striped table-hover">
<thead >
<tr style="font-weight: bold" >
<td>id</td>
<td>Denumire</td>
<td>CUI</td>
<td>Telefon</td>
<td>Email</td>
</tr>
</thead>
</table>
</div>
<input id = "hiddenId" name="hiddenId" type="text" value = {{$someId}} hidden />
</div>
</div>
</div>
#stop
So I need to pass the hidden variable as the second parameter to the "denumire" column hyperlink, something like:
$(nTd).html("<a href='selectieFurnizor?idClient=" + oData.id + "&hiddenId="+$('#hiddenId') "'>" + oData.denumire + "</a>")
.
Is that possible?
The solution which I use now is to return a view from the controller and include in it a static DataTable (with data already prepared and sent by the controller).
Thank you for your attention
:)
Server-side: use add coloumn from controller
$data = DB::table('clienti')->get(['id','denumire','cui','telefon','email']);
return Datatables::of($data)
->addColumn('clear', function ($data) {
return '<i class="glyphicon glyphicon-trash"></i> Clear';
})
->escapeColumns([])
->make(true);
And add to columns with initial js of datatables
{data: 'clear', name: 'cleat', orderable: false, searchable: false }
or use js based columns render() function, official doc and examples here: https://datatables.net/reference/option/columns.render
I am trying to use jquery datatables to output some data from a mysql database.
Here is my route:
Route::get('datatables', ['as' => 'HomeController', 'uses' => 'HomeController#getIndex']);
Route::get('payments-data', ['as' => 'HomeControllerPaymentsData', 'uses' => 'HomeController#Payments']);
My controller HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Carbon\Carbon;
class HomeController extends Controller
{
public function getIndex()
{
return view('payments');
}
/**
* Process datatables ajax request.
*
* #return \Illuminate\Http\JsonResponse
*/
public function Payments()
{
return Datatables::of(DB::table('Payment'))->make(true);
}
Here is my blade/view:
#extends('layouts.master')
#section('content')
<div class="table-responsive">
<table class="table table-hover" id="payments-table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Amount</th>
</tr>
</thead>
</table>
</div>
</div>
#push('scripts')
<script>
$(function() {
$('#payments-table').DataTable({
processing: true,
serverSide: true,
scrollX: true,
ajax: '{!! route('payments-data') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'amount', name: 'amount' },
]
});
});
</script>
#endpush
#endsection
However, when I try to run the route /datatables I get Route [payments-data] not defined. (View: /home/bob/Desktop/dibon/resources/views/payments.blade.php) What could be doing wrong? Anyone.
Use {!! route('HomeControllerPaymentsData') !!} as defined in Route::get('payments-data', ['as' => 'HomeControllerPaymentsData', 'uses' => 'HomeController#Payments']);.
So i create a search engine in my laravel application, the only problem i have is displaying it on the same page,
this is what i have in my views
<div class="search">
{{Form::open(array('url' => 'admin/search', 'method' => 'post'))}}
{{Form::text('keyword',null,array(
'class' => 'form-control',
'placeholder' => 'Enter keyword...'
))}}<br>
{{Form::submit()}}
</div>
<br>
<div class="searchs">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<th>Title</th>
<th>Date Created</th>
<th>Actions</th>
</thead>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</div>
and in my controller
public function search_keyword()
{
$input = Input::get('keyword');
$result = Post::where('title','LIKE','%' .$input. '%')->get();
return Redirect::route('index')
->with('result',$result);
}
but i was hoping that i could do this in ajax request but I don't know jquery or even js.. help
You have to catch the submit of the form with Javascript (vanilla or e.g. jquery), find the value the user is searching for and start an ajax request. (jQuery $.get() or native XMLHttpRequest())
Now you need to make sure that laravel accepts the ajax request properly and return the request as JSON.
If your request successfully returns data, use the success function of the ajax request to process the data. During the search, you could show some loading icon to notify the user that the search process is running.
To start with, add an id to the form and use jquery to listen for the submit event.
<script type="text/javascript">
$('#my-form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "/api/search",
type: 'POST',
data: {
value: $("input:first").val()
},
dataType: 'json',
success: function (response) {
console.log(response);
}
});
});
</script>
Next, register a route for the /api/search request and return your search request with return response()->json(['result' => $result]); (laravel 5)
If everything is right, you should see the result in the console of your browser.