JavaScript Ajax: XMLHttpRequest Object Deep Dive

What is Ajax?

Ajax (Asynchronous JavaScript and XML) is a technique that allows web pages to communicate with servers asynchronously without reloading the entire page. This enables you to update parts of a web page dynamically, creating faster and more responsive web applications.

Basic Example: Simple GET Request

XMLHttpRequest Object Methods

Here are the most commonly used methods of the XMLHttpRequest object:

Method Description Example
open(method, url, async) Initializes a request. Parameters: HTTP method, URL, async (true/false). xhr.open('GET', 'api/data', true)
send(body) Sends the request to the server. Optional body for POST/PUT requests. xhr.send() or xhr.send(JSON.stringify(data))
abort() Aborts the request if it has already been sent. xhr.abort()
setRequestHeader(header, value) Sets the value of an HTTP request header. Must be called after open() but before send(). xhr.setRequestHeader('Content-Type', 'application/json')
getResponseHeader(header) Returns the string containing the text of the specified header. xhr.getResponseHeader('Content-Type')
getAllResponseHeaders() Returns all response headers as a string. xhr.getAllResponseHeaders()
overrideMimeType(mimeType) Overrides the MIME type returned by the server. xhr.overrideMimeType('text/xml')

XMLHttpRequest Object Properties

These properties provide information about the request and response:

Property Description Common Values
readyState Current state of the request 0: UNSENT, 1: OPENED, 2: HEADERS_RECEIVED, 3: LOADING, 4: DONE
status HTTP status code from the server 200: OK, 404: Not Found, 500: Server Error
statusText HTTP status text "OK", "Not Found", "Internal Server Error"
responseText Response data as a string '{"id":1,"title":"Hello"}'
responseXML Response data as XML document XML document object or null
responseType Defines the response type "", "text", "json", "blob", "arraybuffer", "document"
response Response body according to responseType Depends on responseType
timeout Request timeout in milliseconds xhr.timeout = 5000
withCredentials Whether to include cookies in cross-origin requests xhr.withCredentials = true

The onload Property

The onload event handler is triggered when the request completes successfully (regardless of HTTP status code). It's a modern, cleaner alternative to onreadystatechange.

Multiple Callback Functions

You can attach multiple event handlers to handle different aspects of the request:

The onreadystatechange Property

The onreadystatechange event handler is triggered every time the readyState property changes. It's the traditional way to handle Ajax responses.

Ready States Explained:

Value State Description
0 UNSENT Client created, open() not called
1 OPENED open() has been called
2 HEADERS_RECEIVED send() has been called, headers and status available
3 LOADING Downloading, responseText holds partial data
4 DONE Operation complete

Example using onreadystatechange:

Key Differences: onload vs onreadystatechange

Aspect onload onreadystatechange
When triggered Only when request completes (readyState 4) Every time readyState changes
Modern usage Preferred for new code Legacy approach, but still valid
Code clarity Cleaner, focused on completion Can be more complex
Error handling Check status codes manually Check status in readyState 4
Browser support IE9+ (modern browsers) All browsers including old IE

Best Practices

  1. Always check HTTP status codes even when using onload
  2. Handle errors with both onerror and status code checks
  3. Use appropriate response types (responseType property)
  4. Set timeouts for better user experience
  5. Clean up resources when requests are no longer needed
  6. Consider using Fetch API for modern applications (though XMLHttpRequest is still widely used)

This comprehensive understanding of XMLHttpRequest will help you work with Ajax in JavaScript effectively, whether maintaining legacy code or understanding the foundation upon which modern APIs like Fetch are built.