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 Architecture | Overview of how browser and server interact in AJAX communication. |
AJAX โ XMLHttpRequest Object Usage | How to initialize and send requests using XHR methods. |
| AJAX โ Instantiating XHR | Ways to create an XMLHttpRequest object in JS. |
| AJAX โ Core Methods | open(), send(), setRequestHeader() with examples. |
| AJAX โ Key Properties | Understanding readyState, status, responseText, responseXML. |
| AJAX โ GET Request | Example of sending a GET and handling response. |
| ๐ AJAX โ POST Request | Sending POST data and handling a reply. |
| ๐ AJAX โ PUT Request | Sending PUT requests for updates. |
| AJAX โ Send JSON/Data | How to transmit JSON payloads. |
| AJAX โ Handling Text Responses | Managing plain-text responses. |
| AJAX โ Handling Binary Data | Processing Blobs, ArrayBuffers from the server. |
| AJAX โ Handling XML & JSON | Parsing application/xml & application/json responses. |
| ๐๏ธ AJAX โ Callbacks | Named vs anonymous callbacks for async events. |
AJAX โ onreadystatechange Event | Listening for state changes and response processing. |
AJAX โ ClientโServer Architecture
AJAX is just a network convention in the browser:
- Browser triggers a JS event (click/form submit).
- JS creates a request via
XMLHttpRequest. - Server processes and responds (JSON/XML/text).
- 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 requestsend(body): Dispatch itsetRequestHeader(header, value): Define headers
AJAX โ Key Properties
readyState(0โ4): status of requeststatus: 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
readyStateandstatus - 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 :
