Back to the 2023 paper

Module III: Basics of Web Programming

20237m

AJAX (Asynchronous Javascript and XML) is used by web application client to communicate with server side scripts. What four XMLHttpRequest functions are required to make and handle an AJAX call? Write each step in detail.

Worked SolutionAI Assisted

AJAX and XMLHttpRequest

AJAX (Asynchronous JavaScript and XML) is a technique that allows browser JavaScript to communicate with a server asynchronously and update part of a page without a full page reload. JSON is also commonly used today even though the name contains XML.

Main XMLHttpRequest steps

1. Create the request object

const xhr = new XMLHttpRequest();

2. Configure the request with open()

xhr.open("GET", "data.php", true);

open() specifies the HTTP method, URL and whether the request is asynchronous.

3. Handle the response with onreadystatechange

xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        document.getElementById("result").textContent = xhr.responseText;
    }
};

4. Send the request with send()

xhr.send();

For a POST request, data can be supplied to send(data).

Complete example

const xhr = new XMLHttpRequest();

xhr.open("GET", "data.php", true);
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        document.getElementById("result").textContent = xhr.responseText;
    }
};
xhr.send();

Important terms

  • open() → configures request
  • send() → sends request
  • onreadystatechange → reacts to state changes
  • responseText → contains text returned by the server

Exam point: The core request flow is create → open → set handler → send → receive/process response.

Similar questions