JavaScript AJAX Request
An AJAX request is made using the XMLHttpRequest object. The process involves creating the object, configuring the request with open(), and sending it with send(). This chapter covers the XMLHttpRequest approach to making HTTP requests.
The XMLHttpRequest Object
The XMLHttpRequest (XHR) object is the foundation of AJAX. It provides methods and properties for making HTTP requests and handling responses.
// Create a new XMLHttpRequest object
const xhr = new XMLHttpRequest();
console.log('XHR created: ' + typeof xhr);
// Key methods:
console.log('Methods: open(), send(), abort()');
// Key properties:
console.log('readyState: tracks request state (0-4)');
console.log('status: HTTP status code');
console.log('responseText: response as string');
console.log('responseXML: response as XML');open() and send()
The open() method configures the request (method, URL, async flag). The send() method actually sends the request to the server. For POST requests, you pass the data to send() as an argument.
// Syntax: xhr.open(method, url, async)
// method: 'GET', 'POST', 'PUT', 'DELETE'
// url: the server endpoint
// async: true (default) or false
const xhr = new XMLHttpRequest();
// GET request
// xhr.open('GET', 'https://api.example.com/data', true);
// xhr.send(); // No body for GET
// POST request
// xhr.open('POST', 'https://api.example.com/data', true);
// xhr.send(JSON.stringify({ name: 'Alice' }));
console.log('GET: xhr.open("GET", url); xhr.send();');
console.log('POST: xhr.open("POST", url); xhr.send(data);');
console.log('async=true means non-blocking (recommended)');GET vs POST Requests
GET requests retrieve data and append parameters to the URL. POST requests send data in the request body and are used for creating or modifying resources.
| Feature | GET | POST |
|---|---|---|
| Data location | URL query string | Request body |
| Cached | Yes | No |
| Bookmarkable | Yes | No |
| Data size limit | URL length limit (~2048) | No limit |
| Use case | Retrieve data | Submit/modify data |
| Security | Data visible in URL | Data in body (still not encrypted without HTTPS) |
// GET request with query parameters
const getUrl = '/api/users?page=1&limit=10';
console.log('GET URL: ' + getUrl);
// const xhrGet = new XMLHttpRequest();
// xhrGet.open('GET', getUrl);
// xhrGet.send();
// POST request with JSON body
const postData = JSON.stringify({
name: 'Alice',
email: 'alice@example.com'
});
console.log('POST body: ' + postData);
// const xhrPost = new XMLHttpRequest();
// xhrPost.open('POST', '/api/users');
// xhrPost.setRequestHeader('Content-Type', 'application/json');
// xhrPost.send(postData);Request Headers
HTTP headers provide additional information about the request. Use setRequestHeader() to add headers after open() but before send().
const xhr = new XMLHttpRequest();
// xhr.open('POST', '/api/data');
// Common headers
// xhr.setRequestHeader('Content-Type', 'application/json');
// xhr.setRequestHeader('Accept', 'application/json');
// xhr.setRequestHeader('Authorization', 'Bearer token123');
// xhr.setRequestHeader('X-Custom-Header', 'myValue');
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer token123',
'X-Custom-Header': 'myValue'
};
Object.keys(headers).forEach(function(key) {
console.log(key + ': ' + headers[key]);
});Timeout and Abort
You can set a timeout for requests and abort them if needed. The timeout property sets the maximum time (in milliseconds) before the request is terminated.
const xhr = new XMLHttpRequest();
// Set timeout to 5 seconds
xhr.timeout = 5000;
// Handle timeout
xhr.ontimeout = function() {
console.log('Request timed out after ' + xhr.timeout + 'ms');
};
// Abort the request manually
// xhr.abort();
// Handle abort
xhr.onabort = function() {
console.log('Request was aborted');
};
console.log('Timeout: ' + xhr.timeout + 'ms');
console.log('xhr.abort() cancels the request');
console.log('ontimeout fires when timeout is reached');
console.log('onabort fires when request is cancelled');