-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
AJAX allows web pages to send and receive data from the server without reloading, and combining it with a database lets web applications fetch or store data dynamically. This makes websites interactive and user-friendly.
For example, Vicky can build a user management system where Sanjana enters her details, and they are saved to the database and displayed instantly.
AJAX database interaction refers to using AJAX requests in JavaScript to communicate with server-side scripts (PHP, ASP, etc.) that perform database operations. Common tasks include:
Retrieving data from a database.
Inserting new records.
Updating existing records.
Deleting records dynamically.
The server-side script executes the database queries and returns the results, often in JSON or plain text format. The browser then processes the response without page reload.
Let’s assume we have a MySQL database named testdb
with a table called users
:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(50)
);
We want to add new users and display existing users dynamically using AJAX.
fetch_users.php
)<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch users
$sql = "SELECT name, email FROM users";
$result = $conn->query($sql);
$users = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$users[] = $row;
}
}
// Return JSON
header('Content-Type: application/json');
echo json_encode($users);
$conn->close();
?>
function loadUsers() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "fetch_users.php", true);
xhr.onload = function() {
if (xhr.status === 200) {
let users = JSON.parse(xhr.responseText);
let html = "";
users.forEach(user => {
html += `<p>Name: ${user.name}, Email: ${user.email}</p>`;
});
document.getElementById("userList").innerHTML = html;
} else {
document.getElementById("userList").textContent = "Failed to load users";
}
};
xhr.send();
}
document.addEventListener("DOMContentLoaded", loadUsers); // Load users on page load
Explanation:
PHP connects to the database, fetches data, and returns it as JSON.
JavaScript parses the JSON and dynamically displays user data.
<input type="text" id="name" placeholder="Enter name">
<input type="email" id="email" placeholder="Enter email">
<button id="addUser">Add User</button>
<div id="message"></div>
document.getElementById("addUser").addEventListener("click", function() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let xhr = new XMLHttpRequest();
xhr.open("POST", "add_user.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById("message").textContent = xhr.responseText;
loadUsers(); // Refresh user list
} else {
document.getElementById("message").textContent = "Error adding user";
}
};
xhr.send(`name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}`);
});
add_user.php
)<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['name']) && isset($_POST['email'])){
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "User added successfully!";
} else {
echo "Error: " . $conn->error;
}
} else {
echo "Please provide name and email.";
}
$conn->close();
?>
Explanation:
The form sends data via AJAX POST.
PHP inserts the new user into the database.
JavaScript refreshes the displayed user list without reloading the page.
Similarly, AJAX can be used to update or delete database records dynamically. For example:
update_user.php
– Receives user ID and new data, updates the database, and returns a success message.
delete_user.php
– Receives user ID, deletes the record, and returns confirmation.
All updates are handled asynchronously, keeping the user interface smooth.
No page reload is required when fetching or submitting data.
Real-time updates make web applications more interactive.
Users like Sanjana can see changes immediately after Vicky adds new records.
Works with plain text, JSON, or HTML responses from the server.
Using AJAX with databases, developers can:
Retrieve and display data dynamically.
Insert, update, and delete records without page refresh.
Handle JSON or plain text responses for smooth interactions.
Build interactive applications like user management systems, live search, and dashboards.
This approach allows Vicky to create a responsive interface where Sanjana can interact with the database instantly, enhancing the user experience.
Write an AJAX GET request to fetch all users from fetch_users.php
and display them in a <div>
on page load.
Create a form to add a new user (name and email) and send the data via AJAX POST to add_user.php
, then update the user list dynamically.
Write an AJAX request to fetch users in JSON format and display only those whose name is “Sanjana”.
Create a button that deletes a specific user by sending their ID via AJAX POST to delete_user.php
and refreshes the list.
Write an AJAX request to update a user’s email using update_user.php
and display a success message.
Fetch the user list and display it in a table with columns for name and email using AJAX.
Write code to handle errors if fetch_users.php
is missing or the database connection fails, and display an error message in a <div>
.
Create a search input that fetches matching users from the database via AJAX as the user types.
Write an AJAX POST request to insert multiple users at once using a form and display a confirmation message.
Create a function that refreshes the user list every 10 seconds using AJAX to show newly added records without page reload.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts