1

I'm trying to use datatables plugin together with laravel since I need to manage large tables, and the laravel pagination won't be good enough.

I'm using yajra/laravel-datatables component, but I can't get it to work, it throws an error:

DataTables warning: table id=project-table - Ajax error. Fore more information about this error, please see http://datatables.net/tn/7

After reading it, I don't know how to solve it, I'm pretty sure that it has something to do with my routing, because I don't quite understand how the ajax is fetching the result.

This is what I've done:

routes.php

Route::controllers([
'projects'       => 'ProjectController'

]);

ProjectController.php (just the function that fetch the data)

    public function getDataTable()
{
    $projectes = Project::select(['id', 'nom', 'desc', 'preu', 'hores', 'created_at']);

    return Datatables::of($projectes)->make(true);
}

The view:

<table id="project-table" class="table table-condensed table-bordered table-striped">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Titol</th>
                        <th>Desc</th>
                        <th>Preu</th>
                        <th>Hores</th>
                        <th>Data Alta</th>
                    </tr>
                </thead>
            </table>

Finally, the js:

$(function() {
$('#project-table').DataTable({
    processing: true,
    serverSide: true,
    ajax: '{{ url("projects/getDataTable") }}',
    columns: [
        {data: 'id', name: 'id'},
        {data: 'nom', name: 'nom'},
        {data: 'desc', name: 'desc'},
        {data: 'preu', name: 'preu'},
        {data: 'hores', name: 'hores'},
        {data: 'created_at', name: 'created_at'}
    ]
});

});

4
  • Have you followed the debug steps in the help page? What error code are you getting? Commented Jun 23, 2015 at 16:30
  • Yes I forgot to mention that, I'm getting an error code 500 Commented Jun 23, 2015 at 17:01
  • “…since I need to manage large tables, and the laravel pagination won't be good enough.” Why? That’s exactly what pagination is for. Commented Jun 23, 2015 at 19:01
  • Yes, indeed, but I prefer the ajax aproach with datatables plugin. It has a lot of functionality such as sorting and filtering which operates with all the records out of the box Commented Jun 23, 2015 at 19:28

3 Answers 3

2

Change your function to getDatatable (make the T lowercase) in your ProjectController.php. Then change the url in your ajax request to projects/datatable (without the get. Since you used a controller route, the controller will listen for a GET request at projects/datatable).

If that doesn't do it, please post the response when you open the projects/datatable page directly in your browser.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please post your entire controller.php file? Also the entire blade file too.
Well, apparently I made a change and didn't notice it. The naming thing you pointed out was the problem. Thank you BakerStreet!
0

Laravel 5.1 must be installed at the datatables version 6.0:

composer require yajra/laravel-datatables-oracle:~6.0

Comments

0

DataTables Server-side Processing in Laravel

In this tutorial, I will show you the easiest way to implement DataTables jQuery Plugin with remote server side processing in Laravel. Here I will show you how to fetch data from remote MySQL database through ajax in Laravel. For those who don't here about Datatables, DataTables is a table enhancing plug-in for the jQuery Javascript library that helps in adding sorting, paging and filtering abilities to plain HTML tables with minimal effort. The main goal is to enhance the accessibility of data in normal HTML tables.

Now before we start coding include Datatables CSS file and Javascript files from CDN in your view page as follows.

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.css"/>

<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.12/datatables.min.js"></script>

Now let's understand what all tasks we need to do

  1. We need to limit the size of the table. (By default 10,25,50 or 100 entries)
  2. Now Implement search functionality.
  3. The Pagination task.

All above task will be done in the controller and it will be explained later in this tutorial.

Now let's start coding.

In the view page code for HTML table is given below.

 <div class="row">
<div class="col-md-12">
           <table class="table table-bordered" id="posts">
                <thead>
                       <th>Id</th>
                       <th>Title</th>
                       <th>Body</th>
                       <th>Created At</th>
                       <th>Options</th>
                </thead>                
           </table>
    </div>

The javascript code is given below.

script>
$(document).ready(function () {
    $('#posts').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax":{
                 "url": "{{ url('allposts') }}",
                 "dataType": "json",
                 "type": "POST",
                 "data":{ _token: "{{csrf_token()}}"}
               },
        "columns": [
            { "data": "id" },
            { "data": "title" },
            { "data": "body" },
            { "data": "created_at" },
            { "data": "options" }
        ]    

    });
});

Note: Do not forget to pass CSRF Token along with ajax POST request as above. Otherwise, internal server error 500 will occur. This is because Laravel checks CSRF token in all POST controller functions by default to ensure maximum protection.

Now the code for post routes in routes/web.php

Route::post('allposts', 'PostController@allPosts' )->name('allposts');


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

}

Now the code for allPost function in PostController.

public function allPosts(Request $request)
    {

        $columns = array( 
                            0 =>'id', 
                            1 =>'title',
                            2=> 'body',
                            3=> 'created_at',
                            4=> 'id',
                        );

        $totalData = Post::count();

        $totalFiltered = $totalData; 

        $limit = $request->input('length');
        $start = $request->input('start');
        $order = $columns[$request->input('order.0.column')];
        $dir = $request->input('order.0.dir');

        if(empty($request->input('search.value')))
        {            
            $posts = Post::offset($start)
                         ->limit($limit)
                         ->orderBy($order,$dir)
                         ->get();
        }
        else {
            $search = $request->input('search.value'); 

            $posts =  Post::where('id','LIKE',"%{$search}%")
                            ->orWhere('title', 'LIKE',"%{$search}%")
                            ->offset($start)
                            ->limit($limit)
                            ->orderBy($order,$dir)
                            ->get();

            $totalFiltered = Post::where('id','LIKE',"%{$search}%")
                             ->orWhere('title', 'LIKE',"%{$search}%")
                             ->count();
        }

        $data = array();
        if(!empty($posts))
        {
            foreach ($posts as $post)
            {
                $show =  route('posts.show',$post->id);
                $edit =  route('posts.edit',$post->id);

                $nestedData['id'] = $post->id;
                $nestedData['title'] = $post->title;
                $nestedData['body'] = substr(strip_tags($post->body),0,50)."...";
                $nestedData['created_at'] = date('j M Y h:i a',strtotime($post->created_at));
                $nestedData['options'] = "&emsp;<a href='{$show}' title='SHOW' ><span class='glyphicon glyphicon-list'></span></a>
                                          &emsp;<a href='{$edit}' title='EDIT' ><span class='glyphicon glyphicon-edit'></span></a>";
                $data[] = $nestedData;

            }
        }

        $json_data = array(
                    "draw"            => intval($request->input('draw')),  
                    "recordsTotal"    => intval($totalData),  
                    "recordsFiltered" => intval($totalFiltered), 
                    "data"            => $data   
                    );

        echo json_encode($json_data); 

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.