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.
उदाहरण: 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.
उदाहरण: 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.
उदाहरण: 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.
उदाहरण: 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.
उदाहरण: 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
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