Basic Concepts
What is Ajax?
Ajax (Asynchronous JavaScript and XML) is a technique that allows JavaScript to fetch data from a server asynchronously and update parts of a webpage without reloading the entire page.
Key Technologies:
- XMLHttpRequest (XHR) Object: The core object for Ajax communication, used to exchange data with the server in the background.
- JavaScript: Handles client-side logic, user interactions, sending requests, and processing responses.
- HTML/CSS: Builds and styles the user interface.
- XML/JSON: Early Ajax used XML for data transfer; JSON is now more common due to its lightweight nature and ease of use in JavaScript.
Simple Example
Here’s an example of a basic Ajax request to fetch server time and display it on a webpage.
function fetchData(url, callback) {
// Step 1: Create XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Step 2: Configure the request
xhr.open('GET', url, true); // Third parameter true indicates asynchronous request
// Optional: Set callback for request completion
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
// Step 4: Handle successful response
callback(null, xhr.responseText);
} else {
// Handle error
callback(new Error('Request failed with status ' + xhr.status), null);
}
};
// Optional: Set callback for network errors
xhr.onerror = function () {
callback(new Error('Network Error'), null);
};
// Step 3: Send the request
xhr.send();
}
// Usage example
fetchData('https://api.example.com/data', function (error, data) {
if (error) {
console.error('Error fetching data:', error);
} else {
console.log('Data received:', data);
// Update DOM with the returned data here
}
});- Create XMLHttpRequest Object:
var xhr = new XMLHttpRequest();creates the core object for Ajax requests. - Configure Request:
xhr.open('GET', url, true);specifies the request type (GET), URL, and asynchronous execution (true). - Set Callbacks:
xhr.onloadandxhr.onerrorhandle successful responses and network errors, respectively.onloadchecksxhr.statusfor success (200–299). - Send Request:
xhr.send();triggers the HTTP request. - Handle Response: The
callbackfunction processes the result, handling success or failure.
Extensions:
- POST Requests: Change
xhr.opento'POST'and set headers (e.g.,xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');) and a request body (e.g.,xhr.send(JSON.stringify(data));). - JSON Handling: Server responses are often JSON, parsed with
JSON.parse(xhr.responseText). - Error Handling: Refine error logic for specific status codes.
- Cross-Origin Requests: CORS requires server-side headers to allow cross-origin requests.
Principle Analysis
The core principle of Ajax lies in using the XMLHttpRequest (XHR) object to exchange data with the server asynchronously, without blocking the UI or reloading the page. Below is a detailed breakdown of Ajax principles.
- Create XMLHttpRequest Object: The foundation of Ajax communication, enabling requests and responses.
- Open Connection: The
open()method initializes a request with the request type (e.g., GET/POST), URL, and async flag. - Set Callbacks: The
onreadystatechangeevent monitors state changes, processing logic whenreadyStateis 4 andstatusis 200 (success). - Send Request: The
send()method dispatches the request, optionally including a request body for POST. - Handle Response: Callbacks process the response based on
readyState(4 for completion) andstatus(e.g., 200 for success).
// Create XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure request
xhr.open('GET', 'https://api.example.com/data', true);
// Set callback for state changes
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Request successful, process response data
var data = JSON.parse(xhr.responseText);
console.log(data);
} else if (xhr.readyState == 4) {
// Request completed but with error
console.error('Error: ' + xhr.status);
}
};
// Send request
xhr.send();
// For POST request, set headers and send data
// xhr.open('POST', 'https://api.example.com/data', true);
// xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
// xhr.send(JSON.stringify({ key: 'value' }));In-Depth Principles
- Asynchronous Processing: Ajax’s key feature is asynchronicity, allowing scripts to continue executing without waiting for the server response, improving user experience.
- Cross-Origin Issues: Due to the same-origin policy, Ajax requests are restricted by default. CORS allows servers to permit specific cross-origin requests.
- Data Formats: Despite its name, Ajax handles various data types, including JSON (most common), XML, and plain text.
- Modern Alternatives: While XHR is foundational, the Fetch API is increasingly used for its cleaner syntax and Promise support, though the underlying principles are similar.
Server Response Handling (Synchronous vs. Asynchronous)
- responseText: Retrieves response data as a string.
- responseXML: Retrieves response data as XML.
Synchronous Handling
xhr.open("GET", "info.txt", false); // Synchronous request
xhr.send();
document.getElementById("myDiv").innerHTML = xhr.responseText; // Display data directlyAsynchronous Handling
Asynchronous handling is more complex, requiring processing in the request state change event.
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("myDiv").innerHTML = xhr.responseText;
}
};What is readyState?
readyState is a property of the XMLHttpRequest object indicating its current state. It has five possible values (0–4), each representing a different stage:
- 0: Uninitialized –
open()has not been called. - 1: Open –
open()called, butsend()not called. - 2: Sent –
send()called, response not yet received. - 3: Receiving – Partial response data received.
- 4: Complete – All response data received and usable on the client.
What is status?
The HTTP status code (status) is a three-digit number where the first digit defines the response type, and the following two digits provide additional detail. HTTP status codes are grouped into five categories.
Common Status Codes
RFC2616 defines about 40 HTTP status codes, with extensions like WebDAV (RFC4918, 5842) and others (RFC6585) bringing the total to over 60. Below are some representative codes:
- 200: Request processed successfully.
- 204: Request successful, no content returned.
- 301: Permanent redirect – resource assigned a new URI.
- 302: Temporary redirect.
- 304: Resource unchanged; client can use cached version (for conditional GET requests with headers like
If-Match,If-Modified-Since, etc.). - 400: Syntax error in request; client must modify and resend.
- 401: Unauthorized – request requires user authentication.
- 403: Access to resource denied by server.
- 404: Resource not found on server.
- 500: Server error during request processing (e.g., bug or temporary issue).
- 503: Server temporarily overloaded or under maintenance.
GET vs. POST Request Differences
- Parameter Visibility: GET parameters are visible in the URL; POST parameters are sent in the request body via
send(). - Data Volume: GET sends smaller data amounts; POST handles larger data.
- Security and Caching: GET is less secure and often cached; POST is more secure and typically not cached.



