AJAX Tutorial
Estimated reading: 4 minutes 517 views

AJAX Requestโ€ฏ&โ€ฏResponse Lifecycle โ€“ Endโ€‘toโ€‘End Communication Explained


Introduction โ€“ How AJAX Handles Asynchronous Communication

AJAX empowers the browser to communicate with servers without full-page reloads, enabling dynamic, responsive experiences. This lifecycle includes: initializing, sending, receiving, and handling responsesโ€”completely asynchronously. Mastering each phase ensures smooth data flow in your web apps.

In this guide, youโ€™ll learn:

  • Clientโ€“server interaction flow with AJAX
  • Configuring and using XMLHttpRequest
  • GET, POST, PUT lifecycles
  • Handling responses: text, JSON, XML, binary
  • Event handling (onreadystatechange, callbacks)

Topics Covered

Topic Description
AJAX โ€“ Clientโ€‘Server ArchitectureOverview of how browser and server interact in AJAX communication.
AJAX โ€“ XMLHttpRequest Object UsageHow to initialize and send requests using XHR methods.
AJAX โ€“ Instantiating XHRWays to create an XMLHttpRequest object in JS.
AJAX โ€“ Core Methodsopen(), send(), setRequestHeader() with examples.
AJAX โ€“ Key PropertiesUnderstanding readyState, status, responseText, responseXML.
AJAX โ€“ GET RequestExample of sending a GET and handling response.
๐Ÿšš AJAX โ€“ POST RequestSending POST data and handling a reply.
๐Ÿšœ AJAX โ€“ PUT RequestSending PUT requests for updates.
AJAX โ€“ Send JSON/DataHow to transmit JSON payloads.
AJAX โ€“ Handling Text ResponsesManaging plain-text responses.
AJAX โ€“ Handling Binary DataProcessing Blobs, ArrayBuffers from the server.
AJAX โ€“ Handling XML & JSONParsing application/xml & application/json responses.
๐Ÿ–Š๏ธ AJAX โ€“ CallbacksNamed vs anonymous callbacks for async events.
AJAX โ€“ onreadystatechange EventListening for state changes and response processing.

AJAX โ€“ Clientโ€‘Server Architecture

AJAX is just a network convention in the browser:

  1. Browser triggers a JS event (click/form submit).
  2. JS creates a request via XMLHttpRequest.
  3. Server processes and responds (JSON/XML/text).
  4. JS callback updates the UI dynamically.

AJAX โ€“ XMLHttpRequest Object Usage

Core methods:

xhr.open(method, url, async);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(body);

This sets the HTTP method, headers, and body for async transmission.


AJAX โ€“ Instantiating XMLHttpRequest

let xhr = new XMLHttpRequest();
// Optional older IE fallback:
// let xhr = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();

AJAX โ€“ Core Methods

  • open(method, url, async): Initialize your request
  • send(body): Dispatch it
  • setRequestHeader(header, value): Define headers

AJAX โ€“ Key Properties

  • readyState (0โ€“4): status of request
  • status: HTTP status code (200, 404, etc.)
  • responseText, responseXML: raw responses

AJAX โ€“ GET Request Example

let xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data', true);
xhr.onreadystatechange = () => {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();

๐Ÿšš AJAX โ€“ POST Request Example

xhr.open('POST', '/api/users', true);
xhr.setRequestHeader('Content-Type','application/json');
xhr.send(JSON.stringify({ name: 'Alice' }));

๐Ÿšœ AJAX โ€“ PUT Request Example

xhr.open('PUT', '/api/users/123', true);
xhr.setRequestHeader('Content-Type','application/json');
xhr.send(JSON.stringify({ age: 31 }));

AJAX โ€“ Sending JSON & Data Objects

Use JSON for structured payloads:

xhr.setRequestHeader('Content-Type','application/json');
xhr.send(JSON.stringify(obj));

To send form data:

let formData = new FormData(formElement);
xhr.send(formData);

๐Ÿ–Š๏ธ AJAX โ€“ Callback Functions

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) { /* handle response */ }
};
// or:
xhr.onload = () => { /* success */ };
xhr.onerror = () => { /* fail */ };

AJAX โ€“ onreadystatechange Event Handling

Track and respond to each state change:

xhr.onreadystatechange = () => {
  console.log(xhr.readyState, xhr.status);
};

Summary โ€“ Recap & Next Steps

AJAXโ€™s full lifecycleโ€”from request creation to response handlingโ€”powers seamless web experiences:

  • Initiate requests with xhr.open() + xhr.send()
  • Monitor state via readyState and status
  • Decode JSON/XML/text and update UI with callbacks

Understanding this flow grants you fineโ€‘grained control over every AJAX interaction in your apps, from loading data to error handling and beyond.


Frequently Asked Questions (FAQs)

What are the readyState values?
0: Unsent; 1: Opened; 2: Headers received; 3: Loading; 4: Done.

Why use onreadystatechange over onload?
It gives you more control across all stages; onload triggers only upon completion.

Can I send files via AJAX?
Yesโ€”by using FormData and sending it via XHR, or with fetch()/Axios too.

Is synchronous XHR still allowed?
It’s deprecated in browsers; always favor asynchronous requests for good UX.


Share Now :
Share

๐Ÿ” AJAX Request & Response Lifecycle

Or Copy Link

CONTENTS
Scroll to Top