The XMLHttpRequest object is the fundamental component for AJAX operations. It handles sending requests to the server and receiving responses. Modern browsers have built-in support for this object, so no additional libraries are required.
Creating an XMLHttpRequest Instance
let request = new XMLHttpRequest();
Methods of XMLHttpRequest
| Method | Description |
|---|---|
abort() |
Cancels the current request |
getAllResponseHeaders() |
Returns all response headers as a string |
getResponseHeader(headerName) |
Returns the value of a specific response header |
open(method, url, async, user, password) |
Specifies the request parameters: method: HTTP method (e.g., GET, POST) url: target resource location async: boolean (true for asynchronous, false for synchronous) user: optional username for authentication password: optional password for authentication |
send() |
Sends the request to the server; used with GET requests |
send(body) |
Sends the request with a payload; used with POST requests |
setRequestHeader(header, value) |
Adds a header to the request |
Properties of XMLHttpRequest
| Property | Description |
|---|---|
onreadystatechange |
Event handler that fires each time the readyState changes |
readyState |
Holds the current state of the request: 0 – unsent 1 – opened 2 – headers received 3 – loading 4 – done |
responseText |
Returns the response data as a string |
responseXML |
Returns the response data as an XML document |
status |
HTTP status code (e.g., 200, 404, 500) |
statusText |
HTTP status text (e.g., "OK", "Not Found") |
ReadyState Values in Detail
- 0 (UNSENT): The object has been created but
open()has not been called yet. - 1 (OPENED):
open()has been invoked; the request is about to be sent. - 2 (HEADERS_RECEIVED):
send()has been called and headers are available. - 3 (LOADING): The response is being received; partial data is available.
- 4 (DONE): The request is complete and the full response is ready for processing. Check
statusto confirm success.
Common HTTP Status Codes
- 1xx (Informational): Request received, continuing process.
100 Continue – initial part accepted. - 2xx (Success): Request was understood and processed.
200 OK
201 Created
204 No Content - 3xx (Redirection): Further action needed.
301 Moved Permanently
302 Found
304 Not Modified - 4xx (Cleint Error): The request contains bad syntax or cannot be fulfilled.
400 Bad Request
401 Unauthorized
404 Not Found - 5xx (Server Error): The server failed to fulfill a valid request.
500 Internal Server Error
503 Service Unavailable
Using responseText
The responseText property holds the server’s response as a plain string. After a successful request, you can parse this string (e.g., JSON or HTML) and update the page.
let request = new XMLHttpRequest();
request.open("GET", "https://api.example.com/data", true);
request.send();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
let responseData = request.responseText;
console.log(responseData);
// Process the response further
}
};
The open() Method in Depth
open() initializes a request. Its signature is:
request.open(method, url, async, user, password);
method: typically "GET" or "POST".url: relative or absolute path to the resource.async(optional, default true): if false, the request blocks execution until complete.userandpassword(optional): credentials for HTTP authentication.
Example with authentication:
request.open("GET", "https://api.example.com/secure", true, "admin", "secret");