π 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
readyState
andstatus
- 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 :