How to Use jQuery DataTable with AJAX in Laravel

In this tutorial, we'll build a Laravel DataTable example fetching just three columns: Title, Image, and Type, using server-side processing with AJAX.

How to Use jQuery DataTable with AJAX in Laravel Image

DataTables is a powerful jQuery plugin to display tabular data with features like pagination, searching, and sorting. When combined with Laravel and AJAX, it lets you load data dynamically from the server, improving performance.

What You’ll Learn

  • Setup a DataTable in Laravel Blade with AJAX
  • Create a Laravel route and controller for DataTables JSON response
  • Use Laravel Eloquent to fetch and filter data
  • Format JSON response for DataTables consumption
  • Render image thumbnails inside the table

Prerequisites

  • Laravel 9 or 10 installed and configured
  • Basic Laravel knowledge: routes, controllers, views
  • jQuery and DataTables JS & CSS included in your project (via CDN or locally)

Step 1: Create Blade View for the DataTable

Create or open the Blade file where you want to display the posts table, for example: resources/views/admin/posts/index.blade.php

Add this HTML table markup:

<table class="table table-bordered" id="datatable">
    <thead>
        <tr>
            <th>Image</th>
            <th>Title</th>
            <th>Type</th>
        </tr>
    </thead>
</table>

Step 2: Include DataTables and jQuery

Include these in your Blade layout or directly above your script:

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" />

<!-- DataTables JS -->
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>

Step 3: Add JavaScript to Initialize DataTable with AJAX

Below your table or in a JS file, initialize DataTables and configure AJAX:

<script>
$(document).ready(function () {
	$('#datatable').DataTable({
    	"paging": true,
    	"pageLength": 50,
    	"serverSide": true,
    	"lengthChange": true,
    	"searching": true,
    	"ordering": false,
    	"info": true,
    	"autoWidth": false,
    	"ajax": {
        	type: 'POST',
        	url: dataTableUrl,
        	data: function (d) {
            	return $.param(d);
        	},
        	headers: {
            	'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        	},
    	},
    	columns: [
        	{
            	data: 'image', render: function (data) {
                	return `<div class="image-preview">
                            	<img class="table-image-preview1" src="${data}" alt="${data}">
                        	</div>`;
            	}
        	},
        	{ data: 'title' },
        	{ data: 'is_published' },
        	{ data: 'is_highlighted' },
        	{ data: 'author' },
        	{ data: 'type' },
        	{ data: 'published_at' },
        	{ data: 'created_at' },
        	{ data: 'updated_at' },
        	{ data: 'actions' }
    	]
	});
});
</script>

Explanation:

  • serverSide: true means DataTables will send pagination and search parameters to the server.
  • The AJAX call posts to the Laravel route admin.posts.list that we will create next.
  • columns maps JSON keys from server to table columns.
  • The image column uses a custom render function to display an image thumbnail.

Step 4: Define Laravel Route

In your routes/web.php or admin route file:

use App\Http\Controllers\Admin\PostController;

Route::post('/admin/posts/list', [PostController::class, 'list'])->name('admin.posts.list');

Step 5: Implement Controller Method to Serve JSON Data

In app/Http/Controllers/Admin/PostController.php, add the following method:

public function list(Request $request)
{
    $draw = $request->get('draw');
    $start = $request->get('start');
    $length = $request->get('length');
    
    $search = $request->get('search')['value'];
    
    $user = Auth::user();
    $posts = Post::query()->latest();
    
    if (! empty($search)) {
    	$posts->whereLike('title', "%$search%");
    }
    
    $total = $posts->count();
    if ($length >= 0) {
    	$posts->offset($start)->limit($length);
    }
    
    $posts = $posts->get();
    
    $data = [
    	'draw' => $draw,
    	'recordsTotal' => $total,
    	'recordsFiltered' => $total,
    	'data' => PostResource::collection($posts),
    ];
    
    return response()->json($data, 200);
}

Step 6: Create the API Resources

Run commant to create Api Resource file at app/http/resources directory

php artisan make:resource PostResource

now edit toArray function in the PostResource file:

public function toArray(Request $request): array
{
	return [
		'image' => asset('you_image_url'),
		'title' => $this->title,
		'type' => $this->type,
	];
}

Step 7: Add CSRF Token Meta Tag

Make sure your main layout file (resources/views/layouts/app.blade.php or similar) includes the CSRF token meta tag:

<meta name="csrf-token" content="{{ csrf_token() }}">

This is required for Laravel to validate AJAX POST requests.

Step 8: Testing

  • Run your Laravel server: php artisan serve
  • Visit the page with your Blade view
  • You should see a paginated table with Title, Image thumbnails, and Type
  • Try the search box to filter posts by title or type

Summary

In this tutorial, we:

  • Created a Blade table structure for DataTables
  • Initialized DataTables with AJAX pointing to a Laravel route
  • Built a Laravel controller method that fetches paginated, filtered data from the database
  • Returned JSON formatted to DataTables requirements
  • Rendered images inside table cells

Bonus Tips

  • You can extend the controller to add ordering by columns.
  • Add more columns as needed.
  • Use Laravel API Resources for cleaner data formatting.
  • Customize image size and styling in the render function.

Happy Coding! 😊

Do you Like?