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.
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.
Example: Saving Data to a Database via AJAX
// Send a POST request with a JSON body to save-user.php
fetch("save-user.php", {
method: "POST",
headers: { "Content-Type": "application/json" }, // tell the server we're sending JSON
body: JSON.stringify({ name: "Sam" }), // convert the JS object into a JSON string
}).then(r => r.json()).then(confirmation => console.log(confirmation)); // parse and log the server's JSON reply
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.
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.
Example: Handling Loading and Empty States
// Assign "<p>Loading...</p>" to `document.body.innerHTML`
// Assign "<p>Loading...</p>" to `document.body.innerHTML`
document.body.innerHTML = "<p>Loading...</p>";
// Define the method `fetch` taking `"get-users.php"`
// Define the method `fetch` taking `"get-users.php"`
fetch("get-users.php")
// On success, run this with the resolved value as `r`
// On success, run this with the resolved value as `r`
.then(r => r.json())
// On success, run this with the resolved value as `rows`
// On success, run this with the resolved value as `rows`
.then(rows => {
// Assign `rows.length ? JSON.stringify(rows) : "<p>No results</p>"` to `document.body.innerHTML`
// Assign `rows.length ? JSON.stringify(rows) : "<p>No results</p>"` to `document.body.innerHTML`
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.
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