make an ajax request in javascript

To make an AJAX request in JavaScript, we can use the built-in XMLHttpRequest object. The basic steps to make an AJAX request are:

  1. Create an XMLHttpRequest object
  2. Open the request by specifying the HTTP method (GET or POST) and the URL
  3. Set any request headers (e.g. content-type)
  4. Define a callback function to handle the response
  5. Send the request

Here's an example of making a GET request and logging the response to the console:

index.tsx
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    console.log(xhr.responseText);
  }
};
xhr.send();
295 chars
10 lines

This is a simple example, but there are many ways to extend and customize AJAX requests. For example, we can pass data in the request body using POST, use different HTTP headers or methods, or handle errors and timeouts.

gistlibby LogSnag