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.

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:

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:

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:

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:

xhr.send();

Example of a POST request:

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:

const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send();

The load Event

The load event is fired when the request completes successfully.

Example:

const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send();

Handling Errors

Error handling is crucial for a robust application. The onerror event is fired when there is a network error.

Example:

var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://invalid-url.com', true); xhr.onerror = function(error) { console.log('Request failed.'); }; xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send();

Parsing JSON Responses

Often, server responses are in JSON format. You can parse JSON responses using JSON.parse.

Example:

const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true); xhr.onload = function() { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText); console.log('title: ' + data.title); } }; xhr.send();

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 Your Knowledge

Which of the following statements about XMLHttpRequest are correct?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?