Skip to content

XMLHttpRequest

JavaScript is an essential programming language for web development, enabling dynamic and interactive user experiences. One of the key features of JavaScript is its ability to communicate with servers, retrieve data, and update web pages asynchronously. This is primarily achieved through the use of XMLHttpRequest (XHR). This article provides a deep dive into XMLHttpRequest, including its methods, properties, and practical applications, complete with multiple code examples to facilitate learning.

INFO

XMLHttpRequest works with callback functions. You may use Fetch API which deals with promises and is a more modern solution.

Understanding XMLHttpRequest

XMLHttpRequest is a JavaScript object that provides the ability to send HTTP or HTTPS requests to a web server and load the server response data back into the script. This makes it possible to update parts of a web page without reloading the entire page.

Creating an XMLHttpRequest Object

To initiate an XMLHttpRequest, you first need to create an instance of the XMLHttpRequest object:


javascript
const xhr = new XMLHttpRequest();

Making an HTTP Request

Once the XMLHttpRequest object is created, you can configure it to fetch data from a server. The open method is used to set up the request.

The open Method

The open method initializes a request. It takes several parameters:


javascript
xhr.open(method, url, async, user, password);
  • method: The HTTP method to use (e.g., "GET", "POST").
  • url: The URL to which the request is sent.
  • async: A boolean indicating whether the request is asynchronous (true by default).
  • user: Optional, the user name for authentication.
  • password: Optional, the password for authentication.

Example:


javascript
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);

The send Method

The send method sends the request to the server. For a GET request, it is typically called without arguments. For a POST request, you can send data as an argument.

Example of a GET request:


javascript
xhr.send();

Example of a POST request:


javascript
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('param1=value1&param2=value2');

Handling Server Responses

To handle responses from the server, various event listeners can be used.

The onreadystatechange Event

The onreadystatechange event is triggered whenever the readyState property changes. The readyState property holds the status of the XMLHttpRequest.

  • 0: UNSENT
  • 1: OPENED
  • 2: HEADERS_RECEIVED
  • 3: LOADING
  • 4: DONE

You can check the readyState and the status to determine when the request has completed successfully.

Example:


Output appears here after Run.

note

While onreadystatechange works, modern code generally prefers onload and onerror for simpler, more readable request handling. onreadystatechange is mainly used when you need to track intermediate states (like progress or headers received).

The load Event

The load event is fired when the request completes successfully.

Example:


Output appears here after Run.

Handling Errors

Error handling is crucial for a robust application. The onerror event is fired when there is a network error. You can also set a timeout to prevent requests from hanging indefinitely using xhr.timeout (in milliseconds), and handle timeouts with ontimeout.

Example:


Output appears here after Run.

Parsing JSON Responses

Often, server responses are in JSON format. You can parse JSON responses using JSON.parse. Alternatively, you can set xhr.responseType = 'json' to automatically parse the response, which also supports other formats like 'blob', 'arraybuffer', or 'document'.

Example:


Output appears here after Run.

Conclusion

Mastering XMLHttpRequest is fundamental for any web developer aiming to create dynamic and responsive web applications. This guide has covered the essential aspects of XMLHttpRequest, including creating requests, handling responses, error handling, and advanced usage scenarios. By integrating the provided examples into your projects, you can leverage XMLHttpRequest to enhance user experiences and build sophisticated web applications.

Practice

Which of the following statements about XMLHttpRequest are correct?

Dual-run preview — compare with live Symfony routes.