Zap
Documentation / Frontend

DataGrid

VanillaDataGrid enhances a standard HTML table with search, sorting, pagination, column visibility, and CSV/JSON/print export. It uses plain JavaScript with no framework dependency and can enhance locally rendered data or fetch pages from an API.

How it works

DataGrid is distributed as public/assets/js/datagrid.js and public/assets/css/datagrid.css. In Zap, this page loads both registered assets explicitly. In another PHP or JavaScript application, include the script and stylesheet yourself, then initialize VanillaDataGrid after the table is in the DOM.

The table remains the source of its column definitions and, in local mode, its initial row data. DataGrid wraps it with controls and replaces the body with the current result page. Calling destroy() restores the original table and body.

Start with a local HTML table

Mark sortable headers with data-sortable="true". Use data-field for a stable column key and data-type to sort as string, number, or date. Local search and sorting run in the browser.

<table id="orders-table">
 <thead>
 <tr>
 <th data-field="order" data-sortable="true" data-type="number">Order</th>
 <th data-field="customer" data-sortable="true">Customer</th>
 <th data-field="status" data-sortable="true">Status</th>
 <th data-field="total" data-sortable="true" data-type="number">Total</th>
 </tr>
 </thead>
 <tbody>
 <tr><td>1042</td><td>Ada Lovelace</td><td>Paid</td><td>125.50</td></tr>
 <tr><td>1043</td><td>Grace Hopper</td><td>Pending</td><td>89.00</td></tr>
 <tr><td>1044</td><td>Katherine Johnson</td><td>Paid</td><td>240.00</td></tr>
 </tbody>
</table>
const ordersGrid = new VanillaDataGrid('#orders-table', {
 rowsPerPage: 5,
 export: ['csv', 'json', 'print'],
 exportFilename: 'orders',
 labels: {
 search: 'Search orders...',
 empty: 'No matching orders.',
 info: ({ start, end, total }) => `Showing ${start}-${end} of ${total} orders`
 }
});

ordersGrid.ready.then(() => console.log(ordersGrid.getState()));
Order Customer Status Total
1042Ada LovelacePaid125.50
1043Grace HopperPending89.00
1044Katherine JohnsonPaid240.00
1045Dorothy VaughanShipped56.75
1046Mary JacksonPending315.00
1047Margaret HamiltonPaid172.25
1048Joan ClarkeShipped44.00
1049Hedy LamarrPaid98.50

Options and column behavior

  • rowsPerPage (default 5), or the alias pageSize, sets page size. Invalid or non-positive values use the default.
  • searchDebounce controls local/remote search delay in milliseconds (default 300; 0 disables the delay).
  • columns overrides header-derived metadata by column index or field. Supported properties: field, label, sortable, type, and sortValue.
  • type: 'number' parses numeric text (including currency-like labels); type: 'date' uses JavaScript date parsing. Empty sort values remain at the end.
  • export accepts true, one format, or a list of csv, json, and print. Unrecognized formats are ignored.
  • labels can override search, searchLabel, columns, prev, next, page, pagination, loading, empty, error, retry, export labels, and info.
const grid = new VanillaDataGrid('#inventory', {
 rowsPerPage: 20,
 searchDebounce: 200,
 columns: {
 sku: { label: 'SKU', sortable: true },
 price: { type: 'number', sortable: true },
 updated_at: {
 label: 'Updated',
 type: 'date',
 sortValue: (row, text) => Date.parse(text)
 }
 },
 labels: {
 searchLabel: 'Search inventory',
 columns: 'Choose columns',
 info: ({ start, end, total, page, pageSize }) =>
 `${start}-${end} of ${total} (page ${page}, ${pageSize} per page)`
 }
});

A column is sortable only when its header or override enables it. The column menu toggles visibility; setColumnVisible(index, visible) can control the same behavior programmatically.

Load remote, paginated data

Set ajaxUrl for a JSON endpoint, or provide an ajax function. DataGrid sends page, page size, search term, sort field, and sort direction. The default endpoint query keys are page, limit, search, sort, and order. Each returned row is an array of cells in the same order as the table headers.

const remoteGrid = new VanillaDataGrid('#users-table', {
 ajaxUrl: '/api/users',
 rowsPerPage: 25,
 fetchOptions: {
 credentials: 'same-origin',
 headers: { Accept: 'application/json' }
 },
 export: ['csv', 'json'],
 exportScope: 'all',
 maxExportRows: 5000
});

Example JSON response body:

{
 "rows": [
 ["42", "Ada Lovelace", "ada@example.test"],
 ["43", "Grace Hopper", "grace@example.test"]
 ],
 "total": 87
}

The ajax function receives { page, size, query, sort, order, signal } and may return an array or a promise of an array/object. An object must contain a rows or data array and optionally total. Pass signal to fetch so superseded requests can be canceled.

const grid = new VanillaDataGrid('#users-table', {
 ajax: async ({ page, size, query, sort, order, signal }) => {
 const response = await fetch('/api/users?' + new URLSearchParams({
 page,
 limit: size,
 search: query,
 sort,
 order
 }), { signal, headers: { Accept: 'application/json' } });

 if (!response.ok) throw new Error(`Request failed: ${response.status}`);
 return response.json();
 }
});

The backend must apply search, sort, and pagination safely and return the total number of matching rows. Treat the sort field as an allowlisted identifier, never as a raw SQL fragment.

Export data and listen for events

Export includes visible columns and follows the current search and sort. Local grids export all filtered local rows. Remote grids default to exporting only the currently loaded page; set exportScope: 'all' to fetch all matching pages. Remote exports are capped by maxExportRows (default 10,000). CSV cells are quoted and JSON keys come from column fields.

const table = document.querySelector('#orders-table');

table.addEventListener('vdg:load', ({ detail }) => {
 console.log(detail.total, detail.page, detail.rows);
});
table.addEventListener('vdg:search', ({ detail }) => console.log(detail.query));
table.addEventListener('vdg:sort', ({ detail }) => console.log(detail.field, detail.dir));
table.addEventListener('vdg:error', ({ detail }) => console.error(detail.error));

// Programmatic exports use the same configured scope and formats.
ordersGrid.exportCSV();
ordersGrid.exportJSON();
ordersGrid.printTable();

DataGrid emits bubbling vdg:load, vdg:search, vdg:sort, vdg:page, vdg:column, vdg:export, and vdg:error events from the table. Event detail includes the grid instance and event-specific values.

Instance API and cleanup

  • ready is a promise for the current load; getState() returns page, size, query, sort, hidden columns, current rows, total, status, and error.
  • search(term), sort(index, direction), goToPage(page), and reload({ resetPage: true }) return the current load promise.
  • setData(rows) replaces local rows and reloads the grid; it throws when used with a remote source.
  • setColumnVisible(index, visible) toggles a column by zero-based index.
  • getExportData() returns the visible export headers and row text without triggering a download.
  • destroy() cancels pending work, removes generated controls, and restores the original body. Calling methods on a destroyed instance throws.
await ordersGrid.ready;
await ordersGrid.search('Ada');
await ordersGrid.sort(3, 'desc');
ordersGrid.setColumnVisible(2, false);
console.log(await ordersGrid.getExportData());

ordersGrid.destroy();

Accessibility, safety, and limits

  • Keep a semantic table with a header row. DataGrid adds keyboard sorting for sortable headers, sort state, accessible pagination labels, a live status region, and a loading state.
  • Search and sort are not authorization. Filter confidential data on the server and return only records the current user may access.
  • Plain string, number, and { text } cells are escaped. A cell object with { html } is inserted as HTML; use it only for trusted, safely sanitized markup.
  • Remote server sorting must map the requested field to a known database column, and values must be bound as parameters.
  • For large datasets, use remote mode rather than loading all records into the browser. Remote export-all performs multiple page requests and is subject to its row limit.
  • Initializing a table twice throws. Retain the instance and call destroy() before reinitializing or removing a dynamically mounted table.