JS AJAX Database
In this page:
Fetching Database Data via AJAX
A read-only AJAX endpoint runs a database query and returns matching rows as JSON -- the JavaScript side simply fetches and parses that JSON, with no awareness of SQL, tables, or the database engine involved at all.
Note: Keep the client-side JavaScript entirely focused on requesting and rendering data, letting the server own every detail of how that data is actually stored and queried.
Warning: Returning every column from a database table, including ones never used on the client (or worse, sensitive ones), is a common accidental data leak in database-backed AJAX endpoints.
Example: Fetching Database Data via AJAX
fetch("get-users.php")
.then(response => response.json())
.then(rows => console.log(rows)); // JS just parses JSON, no SQL knowledge needed
Saving Data to a Database via AJAX
A write AJAX endpoint reads submitted data, validates it, and inserts or updates it in a database using a prepared statement on the server side -- the JavaScript side sends the request and reads back a confirmation, without any direct knowledge of the database operation that happened.
Note: Design the JSON response from a save endpoint to confirm what actually happened (like returning the new record's ID), giving the JavaScript enough information to update the UI accurately.
Warning: A save endpoint that returns only a generic "success" with no useful data (like the new record's ID) forces the client to make an extra request just to find out what was created.
Example: Saving Data to a Database via AJAX
fetch("save-user.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Sam" }),
}).then(r => r.json()).then(confirmation => console.log(confirmation));
Server-Side Filtering, Sorting, and Pagination
For any dataset large enough to matter, filtering, sorting, and pagination should happen in the server's database query, not by fetching every row and processing it in JavaScript -- the client sends its desired filters as query parameters, and the server's SQL WHERE/ORDER BY/LIMIT does the actual work.
Note: Pass filter, sort, and page parameters as query parameters in the AJAX request, letting the server's database query handle them directly rather than filtering a full dataset client-side.
Warning: Fetching an entire table via AJAX and filtering it in JavaScript works for small datasets but becomes a serious performance problem as the underlying table grows.
Example: Server-Side Filtering, Sorting, and Pagination
const page = 2, sortBy = "name";
fetch(`get-users.php?page=${page}&sort=${sortBy}`)
.then(r => r.json())
.then(rows => console.log(rows)); // filtering/sorting done server-side
Handling Loading and Empty States
A database-backed AJAX request can take a noticeable moment, and might return zero matching rows -- a polished UI shows a loading indicator while waiting, and a clear "no results" message rather than a blank area when the response contains an empty array.
Note: Always design an explicit empty state (a friendly "no results found" message) for any list rendered from an AJAX response, rather than letting an empty array silently produce a blank section.
Warning: Leaving no visual feedback during a database-backed request that takes a second or more can make the interface feel broken or unresponsive, even though it is working correctly.
Example: Handling Loading and Empty States
document.body.innerHTML = "<p>Loading...</p>";
fetch("get-users.php")
.then(r => r.json())
.then(rows => {
document.body.innerHTML = rows.length ? JSON.stringify(rows) : "<p>No results</p>";
});
Error Handling for Database-Backed Endpoints
A database query can fail for reasons entirely outside the client's control -- a connection issue, a constraint violation -- and the server should catch these, log the real detail, and return a generic, safe error message that the JavaScript displays without exposing internal database details to the user.
Note: Design database-backed AJAX endpoints to always return a consistent error shape on failure, so the client-side error handling code stays simple and predictable.
Warning: Displaying a raw database error message directly to the end user (passed through unfiltered from the server) can both confuse users and leak sensitive backend details.
Example: Error Handling for Database-Backed Endpoints
fetch("get-users.php")
.then(response => {
if (!response.ok) throw new Error("Something went wrong");
return response.json();
})
.then(rows => console.log(rows))
.catch(() => console.log("Unable to load data right now")); // no internal DB details exposed
- Building database queries on the server by directly concatenating AJAX-submitted values into SQL, exactly the same SQL injection risk as any other untrusted input.
- Fetching an entire large dataset via AJAX when only a filtered, paginated slice is actually needed, wasting bandwidth and slowing the response.
- Not handling the loading and empty states in the JavaScript UI while waiting for (or after receiving an empty result from) a database-backed AJAX request.
- A database-backed AJAX endpoint runs a query (using prepared statements for any user-supplied values) and returns the result as JSON.
- The client-side JavaScript is unaware of the database entirely -- it only sees the JSON response the server chooses to send.
- Filtering, sorting, and pagination are usually handled on the server side via the database query, not by fetching everything and processing it in JavaScript.
Database-backed AJAX endpoints work identically regardless of server-side language or database engine, since the browser only ever sees the final HTTP response.
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML