← Back to Chapters

JavaScript AJAX

⚡ JavaScript AJAX

⚡ JavaScript AJAX

? Quick Overview

AJAX (Asynchronous JavaScript and XML) is a technique that allows a web page to communicate with a server without reloading the entire page. Although the name mentions XML, modern applications usually exchange data in JSON format.

With AJAX, you can update parts of a web page (like a table, list, or message area) after sending background HTTP requests using JavaScript.

? Key Concepts

  • Asynchronous – the page continues to work while the request is processed in the background.
  • Client-side API – implemented using XMLHttpRequest or the modern fetch() API.
  • Partial page updates – only a specific section of the page is updated, not the whole document.
  • Data formats – commonly JSON; XML and plain text are also possible.
  • HTTP methods – typical AJAX calls use GET (read data) and POST (send data).
  • readyState & status – used with XMLHttpRequest to track request progress and result.
  • RESTful endpoints – predictable URLs for APIs like /users, /posts, etc.
  • Promises – the fetch() API returns a Promise, enabling clean async handling with .then() or async/await.

? Syntax and Flow

In a typical AJAX operation, the flow looks like this:

  1. Create a request object (XMLHttpRequest) or call fetch().
  2. Specify the HTTP method and URL (for example, a REST API endpoint).
  3. Send the request asynchronously.
  4. Wait for the server response (event handler or Promise resolution).
  5. Parse the response (usually JSON).
  6. Update the DOM to show the new data on the page.

? Use Cases

  • Loading new content (posts, comments, products) without reloading the page.
  • Validating form data with the server in real time.
  • Auto-complete suggestions while typing in a search box.
  • Refreshing parts of a dashboard (charts, stats, notifications).

? Code Examples

? Basic GET Request with XMLHttpRequest

Using the older but still supported XMLHttpRequest object:

? View Code Example
// Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);

// Handle state changes and check for a successful response
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    // Parse the JSON response from the server
    const data = JSON.parse(xhr.responseText);
    console.log(data);
  }
};

// Send the request to the server
xhr.send();

? AJAX Using Fetch API (Modern)

The fetch() API returns a Promise and provides a cleaner syntax:

? View Code Example
// Send a GET request using fetch()
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // Handle the parsed JSON data
    console.log(data);
  })
  .catch(error => {
    // Handle any errors that occurred during the request
    console.error('Error:', error);
  });

? Sending Data with POST (XMLHttpRequest)

To send JSON data, set the HTTP method and appropriate headers:

? View Code Example
// Create a new XMLHttpRequest for a POST request
let xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');

// Handle the response from the server
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const responseData = JSON.parse(xhr.responseText);
    console.log(responseData);
  }
};

// Prepare the JSON body to send to the server
const body = {
  name: 'John',
  age: 30
};

// Send the JSON data as a string
xhr.send(JSON.stringify(body));

✉️ POST Request Using Fetch API

The same POST request written using fetch():

? View Code Example
// Send a POST request with JSON data using fetch()
fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John',
    age: 30
  })
})
  .then(response => response.json())
  .then(data => {
    // Log the server's JSON response
    console.log('Server response:', data);
  })
  .catch(error => {
    // Handle any errors from the request
    console.error('Error:', error);
  });

? Live Output / Explanation

?️ Live Demo: Fetching JSON Data

Click the button below to send an AJAX request (using fetch()) to a public test API. The JSON response will be shown in the box.

Click "Load Sample Data" to see the response here.

In this demo:

  • The button triggers a fetch() GET request.
  • When the Promise resolves, the response is converted to JSON.
  • The resulting object is printed into the <pre> block.
  • If any error occurs (network issue, non-OK status), it is caught and displayed.

? Tips & Best Practices

  • Prefer fetch() for modern projects; it has a simpler Promise-based API.
  • Always handle errors with .catch() (for fetch()) or onreadystatechange checks (for XMLHttpRequest).
  • Keep your server endpoints RESTful and well-structured for easier AJAX integration.
  • Use JSON consistently for request and response bodies whenever possible.
  • Avoid blocking the UI; keep requests asynchronous (the default for fetch() and XMLHttpRequest with true).

? Practice Tasks

  • Create a page that makes an AJAX GET request to a public API (for example, users or posts) and displays the results in a list.
  • Use XMLHttpRequest to send a POST request with JSON data and log the server response in the console.
  • Rewrite one of your existing XMLHttpRequest calls using the Fetch API with Promises.
  • Enhance the UI by showing a loading message or spinner while the AJAX request is in progress.