XML - XMLHttpRequest

What is XMLHttpRequest?

XMLHttpRequest is a built-in JavaScript object that lets web pages talk to a server without reloading the entire page.

 Why do we use it?

To do things like:

  • Load new data without refreshing the page.

  • Send user input to a server (like saving a form).

  • Get updates from the server (like new messages in chat).

 Real-life example:

Imagine you're ordering pizza online. You choose toppings and click "Add to Cart" — but the whole page doesn't reload. Behind the scenes, JavaScript uses XMLHttpRequest to send your choice to the server and update the cart instantly.

 How does it work? (Basic steps)

Here's a simple breakdown:

  1. Create the object

    let xhr = new XMLHttpRequest();
    
  2. Set up the request (GET/POST and URL)

    xhr.open("GET", "data.json");
    
  3. Send the request

    xhr.send();
    
  4. Receive and handle the response

    xhr.onload = function () {
      if (xhr.status === 200) {
        console.log(xhr.responseText); // server's reply
      } else {
        console.error("Error loading data");
      }
    };
    

 Important Terms

  • GET – used to get data from the server.

  • POST – used to send data to the server.

  • responseText – the data received from the server.

  • status – tells you if it worked (200 = OK, 404 = Not Found).