AJAX Tutorial
Estimated reading: 4 minutes 40 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ” AJAX Request & Response Lifecycle

Or Copy Link

CONTENTS
Scroll to Top