DeveloperBreeze

$('#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.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

JavaScript in Modern Web Development

  • With Node.js, JavaScript powers the back-end to handle databases, APIs, and server logic.
  • Examples: REST APIs, real-time collaboration tools like Google Docs.

JavaScript isn't limited to the browser anymore. It's being used in diverse domains:

Dec 10, 2024
Read More
Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

use Illuminate\Support\Facades\Http;

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

dd($response->body()); // Display the raw response body
  • Http::post(): This sends a POST request to the specified URL.
  • $response->body(): Returns the raw response body, which can be used as needed.

Oct 24, 2024
Read More
Article

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

To view your project in the browser, you can use a simple HTTP server. Install the live-server package globally:

   npm install -g live-server

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
Tutorial
javascript

مكتبة jQuery: استخدام JavaScript بسهولة وفعالية

<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مثال على jQuery</title>
</head>
<body>

    <h1>مرحبًا بك!</h1>
    <button id="myButton">انقر هنا</button>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // تحديد الزر والتفاعل معه
        $('#myButton').click(function() {
            alert('تم النقر على الزر!');
        });
    </script>
</body>
</html>

شرح الكود:

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

  • The fetch() method returns a Promise that resolves to the Response object representing the entire HTTP response.
  • We check if the response is successful and then parse it as JSON.
  • Any errors during the request are caught and logged.

In many real-world applications, you'll need to send data to the server using POST requests. Here's how to send form data using the Fetch API.

Sep 18, 2024
Read More
Tutorial
css

CSS Variables and Custom Properties: Dynamic Theming and Beyond

const slider = document.getElementById('slider');

slider.addEventListener('input', (e) => {
    document.documentElement.style.setProperty('--spacing-medium', `${e.target.value}px`);
});

Here, a slider adjusts the --spacing-medium value, allowing users to control the layout dynamically.

Sep 05, 2024
Read More
Tutorial
css

Advanced Flexbox Techniques: Creating Responsive and Adaptive Designs

A common challenge is centering items both horizontally and vertically, which Flexbox makes simple:

.container {
    display: flex;
    justify-content: center; /* Center horizontally */
    align-items: center;     /* Center vertically */
    height: 100vh;           /* Full height for vertical centering */
}

Sep 05, 2024
Read More
Tutorial
javascript

Advanced JavaScript Tutorial for Experienced Developers

Symbols were introduced in ES6 as a new primitive data type, alongside strings, numbers, and booleans. A Symbol is a unique and immutable value that can be used as the key for object properties.

const sym1 = Symbol('description');
const sym2 = Symbol('description');

console.log(sym1 === sym2); // Output: false

Sep 02, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

Axios is a powerful and flexible library for making HTTP requests in JavaScript. Whether you're fetching data, submitting forms, or handling complex API interactions, Axios simplifies the process with its clean and consistent API. By mastering the basics covered in this tutorial, you'll be well-equipped to use Axios in your own projects.

  • Experiment with making requests to different APIs.
  • Explore more advanced Axios features like interceptors and request cancellation.
  • Consider using Axios in a framework like React or Vue.js for even more powerful applications.

Sep 02, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

  • Leverage view and pure functions to save gas on reads.

  • Ownable Pattern: Restricts access to certain functions to the contract owner.

Aug 22, 2024
Read More
Cheatsheet

Responsive Design Frameworks Cheatsheet

Tailwind CSS is a utility-first CSS framework that enables styling directly in the markup.

  • Highly customizable and design-consistent.
  • No predefined components, allowing for unique designs.

Aug 21, 2024
Read More
Tutorial
bash

Creating and Managing Bash Scripts for Automation

The first line of a bash script should always be the shebang (#!) followed by the path to the Bash interpreter:

   #!/bin/bash

Aug 19, 2024
Read More
Tutorial
javascript php

Implementing Real-Time Search with Livewire in Laravel

Open the newly created SearchPosts.php file and set up the properties and methods to manage the search query and results:

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Post;

class SearchPosts extends Component
{
    public $query = '';
    public $posts = [];

    public function updatedQuery()
    {
        $this->posts = Post::where('title', 'like', '%' . $this->query . '%')->get();
    }

    public function render()
    {
        return view('livewire.search-posts');
    }
}

Aug 14, 2024
Read More
Code
javascript

React Custom Hook for API Requests

import { useState, useEffect } from 'react';

function useFetch(url, options = {}) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        let isMounted = true; // Track if component is mounted

        const fetchData = async () => {
            setLoading(true);
            try {
                const response = await fetch(url, options);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const result = await response.json();
                if (isMounted) {
                    setData(result);
                }
            } catch (error) {
                if (isMounted) {
                    setError(error);
                }
            } finally {
                if (isMounted) {
                    setLoading(false);
                }
            }
        };

        fetchData();

        return () => {
            isMounted = false; // Cleanup to avoid setting state on unmounted component
        };
    }, [url, options]);

    return { data, loading, error };
}

export default useFetch;

Here’s an example of how to use the useFetch hook in a React component to fetch and display data.

Aug 12, 2024
Read More
Code
python

Python Logging Snippet

  • Add Logging to Your Application: Use this snippet to quickly integrate logging into any Python application.

  • Monitor Application Behavior: By capturing logs, you can gain insights into application behavior, identify issues, and understand the flow of operations.

Aug 08, 2024
Read More
Features 1
Tailwind Component
css html

Features 1

No preview available for this content.

Aug 05, 2024
Read More
Tutorial
json bash

Building Progressive Web Apps (PWAs) with Modern APIs

To set up push notifications, you'll need a server to send push messages. This example demonstrates client-side setup:

// Listen for push events
self.addEventListener('push', event => {
  const data = event.data.json();
  self.registration.showNotification(data.title, {
    body: data.body,
    icon: 'images/icon-192x192.png'
  });
});

Aug 05, 2024
Read More
Tutorial
css html

CSS Grid and Flexbox: Mastering Modern Layouts

<div class="grid-container">
  <div class="grid-item flex-container">
    <div class="flex-item">A</div>
    <div class="flex-item">B</div>
  </div>
  <div class="grid-item">C</div>
</div>
.grid-container {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 10px;
}

.flex-container {
  display: flex;
  justify-content: space-between;
}

Aug 03, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!