Ajax Database in JavaScript
?? Using AJAX with a Database in JavaScript
AJAX by itself cannot access a database directly — it uses JavaScript in the browser to send requests to a server-side script (like PHP, ASP, Node.js), which then interacts with a database (like MySQL, SQL Server, PostgreSQL).
? Basic Flow: AJAX + Server + Database
[ JavaScript (AJAX) ] ?[ Server-side Script (PHP/ASP/Node.js) ] ?[ Database (MySQL/SQL Server/etc.) ] ?[ Return Data ? AJAX ? Update Page ]? Example: AJAX + PHP + MySQL
1. HTML + JavaScript (AJAX)
<input type="text" id="userId" placeholder="Enter User ID"><button onclick="getUserData()">Get User</button><div id="result"></div><script>function getUserData() { const userId = document.getElementById("userId").value; fetch("get_user.php?id=" + encodeURIComponent(userId)) .then(response => response.json()) .then(data => { document.getElementById("result").innerHTML = "Name: " + data.name + "<br>Email: " + data.email; });}</script>2. Server Script (PHP: get_user.php)
<?php$conn = new mysqli("localhost", "root", "", "testdb");$id = $_GET['id'];$sql = "SELECT name, email FROM users WHERE id = ?";$stmt = $conn->prepare($sql);$stmt->bind_param("i", $id);$stmt->execute();$result = $stmt->get_result()->fetch_assoc();echo json_encode($result);?>?? Other Backends You Can Use
| Backend Language | Example File | Database |
|---|---|---|
| PHP | get_user.php | MySQL / MariaDB |
| Classic ASP | get_user.asp | MS Access / SQL Server |
| ASP.NET | GetUser.aspx | SQL Server |
| Node.js | getUser.js | MongoDB / MySQL / etc. |
| Python (Flask) | get_user.py | PostgreSQL / SQLite |
? Output Format
AJAX usually expects:
Text (
text/plain)HTML (
text/html)JSON (
application/json) ? Most common for structured data
? Security Tips
Always validate/sanitize input on the server
Use prepared statements to avoid SQL injection
Never expose DB logic directly to frontend
? Summary
AJAX + JavaScript works with databases by:
Making requests to a backend server script.
That script performs database operations.
It returns the result to JavaScript.
JavaScript updates the webpage dynamically.
Would you like an example using ASP or Node.js instead of PHP?