Aggrid Php Example Updated <RECOMMENDED — 2027>
fetch() API to pull JSON from api.php. This decouples the frontend from the backend, allowing for AJAX refreshes.We need a PHP script that acts as an API. AG Grid sends requests via POST (especially for the Row Model or when updating data).
File: api.php
This script handles two actions:
<?php
// api.php
header("Content-Type: application/json; charset=UTF-8");
// Database Configuration
$host = 'localhost';
$db = 'test_db';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try
$pdo = new PDO($dsn, $user, $pass, $options);
catch (\PDOException $e)
echo json_encode(["error" => $e->getMessage()]);
exit;
// Determine Action based on GET param (or use POST data parsing for stricter APIs)
$action = $_GET['action'] ?? 'fetch';
// 1. HANDLE DATA FETCHING
if ($action === 'fetch')
// Basic SQL
$sql = "SELECT * FROM employees";
$where = [];
$params = [];
// --- FILTERING (Simple Implementation) ---
// AG Grid Filter Model is usually sent via POST or GET depending on config.
// Here we check for simple query params for demonstration:
if (isset($_GET['department']) && !empty($_GET['department']))
$where[] = "department = ?";
$params[] = $_GET['department'];
if (count($where) > 0)
$sql .= " WHERE " . implode(" AND ", $where);
// --- SORTING ---
// AG Grid sends sortModel: [colId: "salary", sort: "asc"]
// We simulate sorting via GET params for this example:
if (isset($_GET['sortCol']) && isset($_GET['sortDir']))
// Validate sortDir to prevent SQL injection
$dir = strtoupper($_GET['sortDir']) === 'DESC' ? 'DESC' : 'ASC';
// Whitelist columns to prevent SQL injection
$allowedCols = ['employee_name', 'salary', 'department'];
if (in_array($_GET['sortCol'], $allowedCols))
$sql .= " ORDER BY " . $_GET['sortCol'] . " " . $dir;
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$data = $stmt->fetchAll();
echo json_encode($data);
// 2. HANDLE ROW UPDATE
elseif ($action === 'update')
AG Grid evolves quickly. The old ways of dumping 10,000 rows to the client and letting the grid filter them no longer work for modern applications.
Old approach (deprecated):
Updated approach (this tutorial):
This updated PHP example uses the Server-Side Row Model, which is now the standard for enterprise-level grids.
Status: [Draft / Ready for Discussion] Context: Integration of AG Grid (JavaScript) with a PHP backend for data retrieval. Objective: Ensure data is delivered efficiently, securely, and in the correct format for the grid to consume. aggrid php example updated
Use code with caution. 🚀 Key Features in this UpdateModern Initialization: Uses agGrid.createGrid(), replacing the older new agGrid.Grid() constructor.
Fetch API: Replaces jQuery AJAX for a dependency-free, native JavaScript experience.
Responsive Design: Uses the flex: 1 property in defaultColDef to ensure the grid fills the screen width.
Security: Uses PHP PDO to prevent SQL injection during data retrieval. 🛠️ Advanced Optimizations
If you are working with millions of rows, consider these additions:
Server-Side Row Model: Instead of loading all data at once, use the serverSide model to fetch data chunks as the user scrolls. New: Use the fetch() API to pull JSON from api
CRUD Integration: Add event listeners like onCellValueChanged to send POST requests back to a PHP update.php script for real-time editing.
Export to Excel: AG Grid Enterprise allows you to export your filtered PHP data directly to .xlsx files.
Implementing AG Grid with PHP involves a two-part architecture: a PHP backend to serve data (usually in JSON format) and a JavaScript frontend to render the grid. 1. The PHP Backend (data.php)
Your PHP script should fetch data from a database and return it as a JSON array. This is the "updated" way to handle modern grid requests.
query("SELECT id, name, model, price FROM cars"); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); // Output as JSON for AG Grid echo json_encode($results); catch (PDOException $e) echo json_encode(['error' => $e->getMessage()]); ?> Use code with caution. Copied to clipboard 2. The Frontend Layout (index.html)
Use the latest AG Grid Community Edition via CDN. The script fetches data from your PHP file using fetch().
Use code with caution. Copied to clipboard Key Update Notes
Grid Initialization: In newer versions (v31+), use agGrid.createGrid() instead of the older new agGrid.Grid().
Data Updates: Use gridApi.setGridOption('rowData', data) to dynamically refresh the grid.
Server-Side Operations: For massive datasets (millions of rows), consider AG Grid Enterprise which allows PHP to handle filtering and sorting directly on the server. Angular Grid: Upgrading to AG Grid 33.0
Create a table products to demonstrate dynamic data updates.
CREATE DATABASE aggrid_demo; USE aggrid_demo;CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, category VARCHAR(100), price DECIMAL(10,2), stock INT DEFAULT 0, last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP );
INSERT INTO products (name, category, price, stock) VALUES ('Laptop Pro', 'Electronics', 1299.99, 25), ('Wireless Mouse', 'Accessories', 29.99, 150), ('Mechanical Keyboard', 'Accessories', 89.50, 75), ('USB-C Hub', 'Cables', 45.00, 40), ('Monitor 27"', 'Electronics', 299.99, 12);We need a PHP script that acts as an API