🔄 AJAX Workflow Diagram

Understanding how AJAX works step by step

Interactive AJAX Workflow Demo

Click "Start AJAX Request" to see the workflow in action:

Ready to start AJAX workflow...
1

📱 User Action Triggers Event

User interacts with the web page (click, form submit, etc.)

// Example: Button click event document.getElementById('loadData').addEventListener('click', function() { makeAjaxRequest(); // Trigger AJAX call });

📁 Browser Components Involved:

User Interface
Button, Form, Link, etc.
JavaScript Event Handler
Listens for user interactions
2

⚙️ Create XMLHttpRequest Object

JavaScript creates an XMLHttpRequest object to handle the request

// Create XMLHttpRequest object const xhr = new XMLHttpRequest(); // Alternative: For older browsers if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { // Code for IE6, IE5 xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
Browser creates
XHR Object
Object initialized
readyState = 0
3

🔧 Configure the Request

Set up the request method, URL, and async flag

// Configure the request xhr.open('GET', 'https://api.example.com/data', true); // Parameters: // 1. Method: GET, POST, PUT, DELETE // 2. URL: API endpoint // 3. Async: true (asynchronous) or false (synchronous)
open() called
readyState = 1
Request Method Set
GET, POST, etc.
URL Configured
API endpoint
4

🎯 Set Up Event Handlers

Define what happens when request state changes and when response arrives

// Set up onreadystatechange handler xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { // Success - process response processResponse(xhr.responseText); } else { // Error handling handleError(xhr.status); } } }; // Modern approach with onload/onerror xhr.onload = function() { if (xhr.status === 200) { processResponse(xhr.response); } }; xhr.onerror = function() { handleError('Network error'); };
5

📤 Send the Request

The request is sent to the server asynchronously

// Send the request xhr.send(); // For POST requests with data xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify({ key: 'value' }));
Browser
Sends HTTP Request
Request Sent
readyState = 2
Headers received
Request In Flight 🚀 → → → → Server Processing
Web Server
Receives & Processes Request
6

🔄 Server Processes Request

Server receives request, processes it, and prepares response

// Server-side example (Node.js/Express) app.get('/api/data', (req, res) => { // Process request const data = fetchFromDatabase(); // Send response res.json({ status: 'success', data: data, timestamp: new Date() }); });
Receive
HTTP Request
Process
Request
Generate
Response
Send
Response
7

📥 Browser Receives Response

Browser receives response in chunks (readyState = 3) then complete (readyState = 4)

// XHR readyState progression during response xhr.onreadystatechange = function() { console.log('ReadyState:', xhr.readyState); switch(xhr.readyState) { case 2: // HEADERS_RECEIVED console.log('Headers received'); break; case 3: // LOADING console.log('Loading response...'); console.log('Partial data:', xhr.responseText); break; case 4: // DONE console.log('Response complete'); handleCompleteResponse(xhr); break; } };
Headers Received
readyState = 2
Downloading Body
readyState = 3
Response Complete
readyState = 4
8

✅ Process the Response

JavaScript processes the response data and updates the DOM

// Process different response types function processResponse(xhr) { const contentType = xhr.getResponseHeader('Content-Type'); if (contentType.includes('application/json')) { const data = JSON.parse(xhr.responseText); updateUIWithData(data); } else if (contentType.includes('text/html')) { document.getElementById('content').innerHTML = xhr.responseText; } else if (contentType.includes('text/xml')) { const xmlDoc = xhr.responseXML; processXML(xmlDoc); } } function updateUIWithData(data) { // Update DOM without page reload document.getElementById('result').innerHTML = `

${data.title}

${data.content}

`; // Update other page elements document.getElementById('status').textContent = 'Updated: ' + new Date().toLocaleTimeString(); }
Parse
Response
Process
Data
Update
DOM
9

🎨 UI Updates Without Reload

The webpage updates dynamically without full page refresh

// Example: Live search results update function updateSearchResults(results) { const resultsContainer = document.getElementById('searchResults'); resultsContainer.innerHTML = ''; results.forEach(result => { const item = document.createElement('div'); item.className = 'result-item'; item.innerHTML = `

${result.title}

${result.description}

`; resultsContainer.appendChild(item); }); // Smooth animation resultsContainer.style.opacity = '0'; setTimeout(() => { resultsContainer.style.opacity = '1'; resultsContainer.style.transition = 'opacity 0.3s ease'; }, 10); }

🔄 Page Update Comparison

🔄
Traditional
Full page reload
White flash
All assets reload
AJAX
Partial update
No flash
Assets cached

🎯 Complete AJAX Workflow Diagram

🌐 Browser Side

1. User interacts with page
2. JavaScript event triggered
3. XMLHttpRequest created
4. Request configured

📡 Network

HTTP Request Sent
← ← ← ← ← ←
HTTP Response Received
→ → → → → →

🖥️ Server Side

5. Server receives request
6. Process request
7. Generate response
8. Send response back
Back to Browser
9. Process Response
Parse data
10. Update DOM
No page reload
11. User Sees Update
Seamless experience

📋 XMLHttpRequest readyState Reference

Value State Description When It Happens
0 UNSENT Client created, open() not called After new XMLHttpRequest()
1 OPENED open() has been called After xhr.open()
2 HEADERS_RECEIVED send() called, headers received Headers arrive from server
3 LOADING Downloading response body Receiving response data
4 DONE Operation complete Response fully loaded

⏱️ AJAX Request Timeline

0ms
User clicks
~5ms
XHR created
~10ms
Request sent
~50-500ms
Network time
~550ms
Response arrives
~560ms
DOM updated
~570ms
User sees update