Async & Promisesmedium

How do you make AJAX calls using the XMLHttpRequest object?

Explain the process of making AJAX calls using the XMLHttpRequest object and how it fits into the asynchronous JavaScript model.

#AJAX#XMLHttpRequest#asynchronous#JavaScript

Answer

  1. Create an instance of XMLHttpRequest.
  2. Use open() method to initialize a request (GET or POST).
  3. Set the onreadystatechange callback to handle response states.
  4. Send the request using the send() method.
  5. In the callback, check readyState and status to access response data.

Trade-offs:

  • XMLHttpRequest can be more verbose compared to the Fetch API.
  • Better compatibility with older browsers.

Practise more Async & Promises questions →