DeveloperBreeze

Dynamic and Responsive DataTable with Server-Side Processing and Custom Styling

$('#exampleTable').DataTable({
    "responsive": true,
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "{{ route('fetchUserData') }}",
        "type": "GET",
        "error": function(xhr, status, errorThrown) {
            console.error("Error during AJAX request: ", errorThrown);
        },
        "dataSrc": function(response) {
            console.info("Data received from server: ", response);
            if (response.records && response.records.length) {
                console.info("Data entries loaded:");
                response.records.forEach(function(record) {
                    console.log(record);
                });
                return response.records;
            } else {
                console.warn("No records found.");
                return [];
            }
        }
    },
    "columns": [
        { "data": "username" },
        { "data": "points" },
        { "data": "followers" },
        { "data": "referrals" }
    ],
    "language": {
        "emptyTable": "No records to display" // Custom message for empty table
    },
    "initComplete": function() {
        $('div.dataTables_length select').addClass('form-select mt-1 w-full');
        $('div.dataTables_filter input').addClass('form-input block w-full mt-1');
    },
    "drawCallback": function() {
        $('table').addClass('min-w-full bg-gray-50');
        $('thead').addClass('bg-blue-100');
        $('thead th').addClass('py-3 px-5 text-left text-xs font-semibold text-gray-700 uppercase tracking-wide');
        $('tbody tr').addClass('border-t border-gray-300');
        $('tbody td').addClass('py-3 px-5 text-sm text-gray-800');
    }
});

Explanation of the Code Snippet

This JavaScript code initializes a DataTables instance on an HTML table with the ID #exampleTable. It enhances the table with various features like responsiveness, server-side processing, AJAX data fetching, and custom styling.

Key Features:

  1. Responsive Table:
  • responsive: true makes the table adapt to different screen sizes.
  1. Server-Side Processing:
  • serverSide: true enables server-side pagination, sorting, and filtering.
  • processing: true displays a processing indicator while fetching data.
  1. AJAX Configuration:
  • The ajax object defines how data is fetched from the server.
  • url: Endpoint for fetching data.
  • type: HTTP method (GET).
  • error: Logs errors that occur during the AJAX request.
  • dataSrc: Processes the server's response. It logs the data and returns records for display.
  1. Column Definitions:
  • The columns array specifies how data fields (e.g., username, points) map to table columns.
  1. Custom Language:
  • language.emptyTable: Custom message displayed when no data is available.
  1. Initialization Customization:
  • initComplete: Adds custom classes to dropdowns and inputs in the DataTables UI for consistent styling.
  1. Draw Callback:
  • drawCallback: Applies custom classes to various table elements (e.g., rows, headers, cells) after each table draw to enhance the appearance.

Related Posts

More content you might like

Tutorial
javascript

JavaScript in Modern Web Development

  • JavaScript is used in IoT devices for controlling hardware and sensors.
  • Example: Node.js-based IoT applications.
  • Libraries like Three.js and Babylon.js enable building browser-based games.
  • Example: Interactive 3D experiences.

Dec 10, 2024
Read More
Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

If the raw response is in the form of a query string (e.g., key1=value1&key2=value2), you can use PHP’s built-in parse_str() function to convert it into an associative array.

use Illuminate\Support\Facades\Http;

$response = Http::post('https://api.example.com/endpoint', [
    'key1' => 'value1',
    'key2' => 'value2',
]);

$rawResponse = $response->body(); // Get the raw response
$parsedResponse = [];

// Parse the query string into an associative array
parse_str($rawResponse, $parsedResponse);

dd($parsedResponse); // Now you can work with the associative array

Oct 24, 2024
Read More
Article

Integrating Flowbite with Tailwind CSS: A Step-by-Step Tutorial

  • Node.js and npm Installed: Tailwind CSS and Flowbite are Node.js-based tools. Download and install Node.js from the official website, which includes npm.
  • Basic Knowledge of HTML and CSS: Familiarity with HTML structure and CSS will help you follow along more effectively.
  • Code Editor: Use any code editor of your choice, such as Visual Studio Code.

Open your terminal or command prompt and create a new directory for your project:

Oct 24, 2024
Read More
Article
javascript

20 Useful Node.js tips to improve your Node.js development skills:

No preview available for this content.

Oct 24, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!