AJAX - Callbacks in AJAX

1) What is a Callback?

A callback is a function you pass into another function, to be executed later when an asynchronous operation (like AJAX) finishes.

  • AJAX requests are asynchronous → they don’t block the page.

  • Instead of immediately returning data, you provide a callback function that will run when the response arrives.


2) Callback Flow in AJAX

  1. You start an AJAX request.

  2. While waiting, JavaScript continues running other code.

  3. When the server responds, the callback is triggered with the result (or error).


3) Example with XMLHttpRequest

function getData(url, successCallback, errorCallback) {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);

  xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
      successCallback(xhr.responseText);  // call success handler
    } else {
      errorCallback(`HTTP Error: ${xhr.status}`);
    }
  };

  xhr.onerror = function() {
    errorCallback("Network error");
  };

  xhr.send();
}

// Usage
getData(
  "/api/user",
  function success(data) {
    console.log("Data received:", data);
  },
  function error(err) {
    console.error("Request failed:", err);
  }
);

4) Example with jQuery AJAX (callback style)

$.ajax({
  url: "/api/user",
  method: "GET",
  success: function(data) {
    console.log("Success:", data); // success callback
  },
  error: function(xhr, status, error) {
    console.error("Error:", status, error); // error callback
  }
});

5) Pros and Cons of Callbacks

Advantages

  • Simple to understand.

  • Widely used in older codebases and libraries.

  • Works in all browsers (no modern syntax required).

 Disadvantages

  • Callback Hell (nested callbacks become unreadable):

    getUser(1, function(user) {
      getPosts(user.id, function(posts) {
        getComments(posts[0].id, function(comments) {
          console.log(comments);
        });
      });
    });
    
  • Harder to handle errors across multiple async steps.

  • Modern alternatives (Promises, async/await) are cleaner.


6) Callback vs Promise vs Async/Await (Quick Contrast)

  • Callback (old way):

    getData("/api/user", (data) => console.log(data));
    
  • Promise (modern):

    fetch("/api/user")
      .then(res => res.json())
      .then(data => console.log(data))
      .catch(err => console.error(err));
    
  • Async/Await (cleanest):

    async function loadUser() {
      try {
        const res = await fetch("/api/user");
        const data = await res.json();
        console.log(data);
      } catch (err) {
        console.error(err);
      }
    }
    loadUser();
    

Summary:

  • Callbacks were the traditional way of handling AJAX responses.

  • They are still supported and useful for simple cases, but for complex async flows, modern approaches (Promises and async/await) are preferred.