Выберите город
100% гарантия применимости ✓ Честная гарантия ✓ Упрощенный возврат

Aggrid Php Example Updated ❲2026 Release❳

In this example, we've created a simple AG Grid table using PHP and MySQL. We've demonstrated how to fetch data from a database and display it in an interactive table. AG Grid offers a wide range of features and customization options, making it a powerful tool for creating dynamic and interactive tables.


This is the "Updated" part. We use modern AG Grid syntax, enabling Enterprise-style features (like editing) using the Community version.

File: index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>AG Grid PHP Updated Example</title>
    <!-- Ag-Grid CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ag-grid-community/styles/ag-grid.css"/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ag-grid-community/styles/ag-theme-alpine.css"/>
    <style>
        #myGrid  height: 500px; width: 100%; 
    </style>
</head>
<body>
<div id="myGrid" class="ag-theme-alpine"></div>
<!-- Ag-Grid JS -->
<script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script>
<script>
    // Define Column Definitions
    const columnDefs = [
         field: 'id', hide: true , // ID is hidden but needed for updates
         field: 'employee_name', filter: true, editable: true ,
         field: 'job_title', editable: true ,
         field: 'department', filter: true, editable: true ,
field: 'salary', 
            editable: true, 
            valueFormatter: params => '$' + params.value.toLocaleString(),
            filter: 'agNumberColumnFilter'
];
// Grid Options
    const gridOptions = 
        columnDefs: columnDefs,
        rowData: null, // Start empty
        defaultColDef: 
            flex: 1,
            minWidth: 100,
            sortable: true
        ,
        // Enable editing
        editType: 'fullRow', // Edit whole row at once
        onRowValueChanged: onRowValueChanged // Event listener for saves
    ;
// Initialize Grid
    document.addEventListener('DOMContentLoaded', () => 
        const gridDiv = document.querySelector('#myGrid');
        new agGrid.Grid(gridDiv, gridOptions);
// Fetch initial data
        fetchGridData();
    );
// Function to fetch data from PHP
    function fetchGridData() 
        // Example: Add sorting params if needed manually, or use AG Grid datasource
        fetch('api.php?action=fetch')
            .then(response => response.json())
            .then(data => 
                gridOptions.api.setRowData(data); // Updated API method
            )
            .catch(err => console.error('Error fetching data:', err));
// Function to handle data update (Backend Sync)
    function onRowValueChanged(event) 
        const newData = event.data;
console.log('Saving changes:', newData);
fetch('api.php?action=update', 
            method: 'POST',
            headers:  'Content-Type': 'application/json' ,
            body: JSON.stringify(newData)
        )
        .then(response => response.json())
        .then(res => 
            if (res.success) 
                console.log('Database updated successfully');
                // Optional: Show a toast notification
             else 
                alert('Error updating database: ' + res.message);
                // Optional: Revert the grid change
);
</script>
</body>
</html>

  • New: Use the fetch() API to pull JSON from api.php. This decouples the frontend from the backend, allowing for AJAX refreshes.
  • Updated index.html – Using AG Grid’s Server-Side Row Model (recommended for large data) OR Infinite Row Model. Here we use the Server-Side Row Model for efficiency.

    <!DOCTYPE html>
    <html>
    <head>
        <title>AG Grid + PHP Example (Updated)</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ag-grid-community/styles/ag-grid.css">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ag-grid-community/styles/ag-theme-alpine.css">
        <script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script>
    </head>
    <body>
    <div id="myGrid" style="height: 600px; width: 100%;" class="ag-theme-alpine"></div>
    

    <script> const columnDefs = [ field: "id", sortable: true, filter: "agNumberColumnFilter", width: 90 , field: "name", sortable: true, filter: "agTextColumnFilter", editable: true , field: "category", sortable: true, filter: "agTextColumnFilter", editable: true , field: "price", sortable: true, filter: "agNumberColumnFilter", editable: true, cellRenderer: "agAnimateShowChangeCellRenderer" , field: "stock", sortable: true, filter: "agNumberColumnFilter", editable: true , headerName: "Actions", cellRenderer: (params) => return <button onclick="deleteRow($params.data.id)">Delete</button>; , width: 100 ]; aggrid php example updated

    const gridOptions = 
        columnDefs: columnDefs,
        rowModelType: 'serverSide',
        serverSideStoreType: 'partial',
        pagination: true,
        paginationPageSize: 25,
        cacheBlockSize: 25,
        maxBlocksInCache: 2,
        animateRows: true,
        enableCellEditing: true,
        onCellValueChanged: (event) => updateRow(event.data),
    ;
    // Server-side datasource
    const createServerSideDatasource = (server) => 
        return 
            getRows: (params) => 
                const request = 
                    startRow: params.request.startRow,
                    endRow: params.request.endRow,
                    sortModel: params.request.sortModel,
                    filterModel: params.request.filterModel
                ;
    fetch(`server.php?action=getRows&startRow=$request.startRow&endRow=$request.endRow&sortModel=$JSON.stringify(request.sortModel)&filterModel=$JSON.stringify(request.filterModel)`)
                    .then(response => response.json())
                    .then(data => 
                        if (data.success) 
                            params.success( rowData: data.rows, rowCount: data.lastRow );
                         else 
                            params.fail();
    )
                    .catch(error => 
                        console.error('Error fetching data', error);
                        params.fail();
                    );
    ;
    ;
    // Initialize grid
    const gridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(gridDiv, gridOptions);
    const datasource = createServerSideDatasource();
    gridOptions.api.setServerSideDatasource(datasource);
    // CRUD functions
    async function addRow() 
        const newRow =  name: 'New Product', category: 'General', price: 0, stock: 0 ;
        const response = await fetch('server.php?action=addRow', 
            method: 'POST',
            headers:  'Content-Type': 'application/json' ,
            body: JSON.stringify(newRow)
        );
        if (response.ok) 
            gridOptions.api.refreshServerSideStore( purge: true );
    async function updateRow(data) 
        await fetch('server.php?action=updateRow', 
            method: 'PUT',
            headers:  'Content-Type': 'application/json' ,
            body: JSON.stringify(data)
        );
    async function deleteRow(id) 
        await fetch(`server.php?action=deleteRow&id=$id`,  method: 'DELETE' );
        gridOptions.api.refreshServerSideStore( purge: true );
    // Add button outside grid
    const btn = document.createElement('button');
    btn.innerText = 'Add New Product';
    btn.onclick = addRow;
    document.body.insertBefore(btn, gridDiv);
    

    </script> </body> </html>


    Create an HTML file called "index.html" and add the following code:

    <!DOCTYPE html>
    <html>
    <head>
        <title>AG Grid PHP Example</title>
        <script src="https://unpkg.com/ag-grid-community/dist/ag-grid-community.min.noStyle.js"></script>
        <link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-grid.css">
        <link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-theme-balham.css">
    </head>
    <body>
        <div id="grid" style="height: 200px; width: 400px;" class="ag-theme-balham"></div>
        <script>
            // Fetch data from PHP script
            fetch('grid.php')
                .then(response => response.json())
                .then(data => 
                    // Create AG Grid
                    const gridOptions = 
                        columnDefs: [
                             field: 'name' ,
                             field: 'email' ,
                             field: 'department' 
                        ],
                        rowData: data
                    ;
    new agGrid.Grid(document.getElementById('grid'), gridOptions);
                );
        </script>
    </body>
    </html>
    

    This HTML file includes the AG Grid library and creates a simple grid with three columns. It then fetches data from the "grid.php" script and passes it to the AG Grid. In this example, we've created a simple AG

    Let’s define a simple dataset to manipulate. Run this SQL in your database:

    CREATE TABLE employees (
        id INT AUTO_INCREMENT PRIMARY KEY,
        employee_name VARCHAR(100),
        job_title VARCHAR(100),
        department VARCHAR(50),
        salary INT
    );
    INSERT INTO employees (employee_name, job_title, department, salary) VALUES
    ('Alice Johnson', 'Software Engineer', 'Engineering', 95000),
    ('Bob Smith', 'Project Manager', 'Operations', 85000),
    ('Charlie Davis', 'UX Designer', 'Product', 78000),
    ('Diana Evans', 'Data Analyst', 'Marketing', 72000);
    

    Наверх