Understanding AJAX and Asynchronous Communication
AJAX (Asynchornous JavaScript and XML) enables web applications to exchange data with servers asynchronously without full page reloads. This approach improves user experience by allowing partial page updates.
Synchronous vs. Asynchronous Requests
Synchronous requests block user interaction until completion, while asynchronous requests allow continued user interaction during server communication.
Core AJAX Implementation
Using native XMLHttpRequest involves creating the object, configuring the request, sending it, and handling the response.
// Native AJAX implementation
function sendAjaxRequest() {
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data-endpoint', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const serverResponse = xhr.responseText;
processResponseData(serverResponse);
}
};
xhr.send();
}
Streamlining with Axios
Axios simplifies AJAX implementation by providing a cleaner API with promise-based responses.
// Basic Axios GET request
axios.get('/api/user-data?userId=12345')
.then(response => {
console.log('Received data:', response.data);
updateUserInterface(response.data);
})
.catch(error => {
console.error('Request failed:', error);
displayErrorMessage(error.message);
});
// POST request with JSON data
const userData = { username: 'john_doe', email: 'john@example.com' };
axios.post('/api/user-create', userData)
.then(response => {
console.log('User created:', response.data);
});
Working with JSON Data Format
JSON serves as the standard data interchange format between client and server.
// JSON structure examples
const productInfo = {
"productId": "P1001",
"productName": "Wireless Headphones",
"price": 129.99,
"inStock": true,
"specifications": ["Bluetooth 5.0", "20h battery", "Noise cancellation"]
};
// JSON serialization and parsing
const jsonString = JSON.stringify(productInfo);
const parsedObject = JSON.parse(jsonString);
Java JSON Processing with Fastjson
Server-side JSON processing in Java can be handled efficiently with libraries like Fastjson.
// Server-side JSON handling with Fastjson
@WebServlet("/product-data")
public class ProductServlet extends HttpServlet {
private ProductService productService = new ProductService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
List<product> products = productService.getAllProducts();
String jsonResponse = JSON.toJSONString(products);
resp.setContentType("application/json;charset=UTF-8");
resp.getWriter().write(jsonResponse);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
BufferedReader reader = req.getReader();
String jsonData = reader.readLine();
Product newProduct = JSON.parseObject(jsonData, Product.class);
productService.addProduct(newProduct);
resp.getWriter().write("{\"status\":\"success\"}");
}
}
</product>
Practical Application: Product Management System
Building a complete product management system demonstrates AJAX, Axios, and JSON integration.
Database Setup
-- Product table structure
CREATE TABLE products (
product_id INT PRIMARY KEY AUTO_INCREMENT,
product_name VARCHAR(100) NOT NULL,
category VARCHAR(50),
unit_price DECIMAL(10,2),
stock_quantity INT,
description TEXT,
active_status BOOLEAN DEFAULT TRUE
);
-- Sample data
INSERT INTO products (product_name, category, unit_price, stock_quantity, description)
VALUES ('Wireless Mouse', 'Electronics', 29.99, 150, 'Ergonomic wireless mouse'),
('Mechanical Keyboard', 'Electronics', 89.99, 75, 'RGB mechanical keyboard');
Client-Side Implementation
<title>Product Management</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<button onclick="loadProducts()">Load Products</button>
<div id="productTableContainer"></div>
<script>
async function loadProducts() {
try {
const response = await axios.get('/api/products');
const products = response.data;
renderProductTable(products);
} catch (error) {
console.error('Failed to load products:', error);
}
}
function renderProductTable(products) {
const tableHTML = `
<table border="1">
<thead>
<tr>
<th>ID
<th>Name
<th>Category
<th>Price
<th>Stock
<th>Status
<tbody>
${products.map(product => `
<tr>
<td>${product.productId}
<td>${product.productName}
<td>${product.category}
<td>$${product.unitPrice}
<td>${product.stockQuantity}
<td>${product.activeStatus ? 'Active' : 'Inactive'}
`).join('')}
`;
document.getElementById('productTableContainer').innerHTML = tableHTML;
}
</script>
Product Creation Form
// Product creation with form data
document.getElementById('createProductForm').addEventListener('submit', async (e) => {
e.preventDefault();
const productData = {
productName: document.getElementById('productName').value,
category: document.getElementById('productCategory').value,
unitPrice: parseFloat(document.getElementById('unitPrice').value),
stockQuantity: parseInt(document.getElementById('stockQuantity').value),
description: document.getElementById('description').value,
activeStatus: document.getElementById('activeStatus').checked
};
try {
const response = await axios.post('/api/products/create', productData);
if (response.data.status === 'success') {
alert('Product created successfully');
loadProducts(); // Refresh the product list
e.target.reset(); // Clear the form
}
} catch (error) {
console.error('Product creation failed:', error);
alert('Failed to create product');
}
});
Error Handling and Best Practices
Robust AJAX implementations require proper error handling and validation.
// Comprehensive error handling
async function fetchProductDetails(productId) {
try {
const response = await axios.get(`/api/products/${productId}`, {
timeout: 5000,
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
return response.data;
} else {
throw new Error(`Server returned status: ${response.status}`);
}
} catch (error) {
if (error.response) {
// Server responded with error status
console.error('Server error:', error.response.status);
} else if (error.request) {
// No response received
console.error('Network error:', error.message);
} else {
// Configuration error
console.error('Request setup error:', error.message);
}
return null;
}
}