Displaying a Progress Bar for AJAX Requests – A Complete Guide
Introduction
In modern web applications, AJAX (Asynchronous JavaScript and XML) is widely used to load data dynamically without reloading the page. However, when dealing with long-running AJAX requests, users may feel uncertain about whether the request is still processing or has stalled.
A progress bar provides visual feedback that an AJAX request is in progress, helping improve user experience and engagement. In this guide, we will explore various ways to implement and customize a progress bar for AJAX requests.
What Will You Learn?
- Why Use a Progress Bar for AJAX Requests?
- Understanding AJAX Request States
- Implementing a Simple Progress Bar with jQuery AJAX
- Using jQuery UI Progress Bar
- Tracking Progress of File Uploads Using
XMLHttpRequest
- Using Bootstrap Progress Bar with AJAX
- Handling Errors and Edge Cases in Progress Bars
- Optimizing AJAX Performance with Progress Indicators
- Real-World Use Cases for AJAX Progress Bars
- Best Practices for Implementing AJAX Progress Bars
1. Why Use a Progress Bar for AJAX Requests?
A progress bar in AJAX requests enhances user experience by:
✅ Providing Feedback – Prevents user confusion by indicating progress.
✅ Improving User Engagement – Keeps users informed while waiting.
✅ Preventing Multiple Submissions – Stops users from clicking the same button multiple times.
✅ Enhancing UI/UX – Looks professional and helps with usability.
2. Understanding AJAX Request States
AJAX requests typically go through various states before completing:
- Initiation – The request is sent.
- Processing – The server processes the request.
- Completion – The response is received.
- Failure – The request fails due to network or server issues.
A progress bar should visually reflect these states in real time.
3. Implementing a Simple Progress Bar with jQuery AJAX
We can use jQuery and CSS to create a basic AJAX progress bar.
Step 1: Create the Progress Bar in HTML
<div id="progress-container" style="width: 100%; background: #ccc; display: none;">
<div id="progress-bar" style="width: 0%; height: 20px; background: blue;"></div>
</div>
<button id="startAjax">Start AJAX Request</button>
Step 2: Write the jQuery AJAX Code
$(document).ready(function() {
$("#startAjax").click(function() {
$("#progress-container").show(); // Show progress bar
$("#progress-bar").css("width", "0%"); // Reset progress
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
type: "GET",
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
$("#progress-bar").css("width", percentComplete + "%");
}
};
return xhr;
},
success: function(response) {
console.log("Data loaded successfully");
$("#progress-bar").css("width", "100%");
setTimeout(() => $("#progress-container").fadeOut(), 1000);
},
error: function() {
alert("Failed to load data.");
$("#progress-container").hide();
}
});
});
});
How It Works:
- The progress bar is initially hidden and shown only when the AJAX request starts.
- The
xhr.onprogress
event updates the progress bar width dynamically. - On completion, the progress bar reaches 100%, then fades out.
4. Using jQuery UI Progress Bar
If you’re using jQuery UI, you can enhance the progress bar.
Step 1: Add jQuery UI to Your Page
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Step 2: Modify HTML for jQuery UI Progress Bar
<div id="progressbar"></div>
<button id="loadData">Load Data</button>
Step 3: Implement jQuery UI Progress Bar
$(document).ready(function() {
$("#progressbar").progressbar({ value: 0 });
$("#loadData").click(function() {
$("#progressbar").progressbar("value", 0); // Reset progress
$("#progressbar").show();
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
type: "GET",
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
$("#progressbar").progressbar("value", percentComplete);
}
};
return xhr;
},
success: function() {
$("#progressbar").progressbar("value", 100);
setTimeout(() => $("#progressbar").fadeOut(), 1000);
}
});
});
});
Benefits of jQuery UI Progress Bar
✅ Stylish and Customizable
✅ Built-in jQuery UI Effects
✅ Easy Integration
5. Tracking Progress of File Uploads Using XMLHttpRequest
For file uploads, the progress bar tracks upload progress instead of download progress.
Step 1: Create an HTML Form
<input type="file" id="fileInput">
<button id="uploadBtn">Upload File</button>
<div id="uploadProgress">
<div id="uploadBar" style="width: 0%; height: 20px; background: green;"></div>
</div>
Step 2: Implement AJAX File Upload with Progress Tracking
$("#uploadBtn").click(function() {
var file = $("#fileInput")[0].files[0];
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
$("#uploadBar").css("width", percentComplete + "%");
}
};
xhr.open("POST", "upload.php", true);
xhr.send(formData);
xhr.onload = function() {
if (xhr.status === 200) {
alert("Upload successful!");
$("#uploadBar").css("width", "100%");
} else {
alert("Upload failed.");
}
};
});
Why Use XMLHttpRequest
for Uploads?
✅ Tracks Upload Progress in Real-Time
✅ Works for Large File Uploads
✅ Better User Experience for Uploading
6. Using Bootstrap Progress Bar with AJAX
If you are using Bootstrap, you can integrate a Bootstrap progress bar.
Step 1: Add Bootstrap Progress Bar
<div class="progress">
<div id="bootstrapProgress" class="progress-bar progress-bar-striped" style="width: 0%;"></div>
</div>
<button id="startAjax">Start AJAX</button>
Step 2: Implement Progress Tracking
$("#startAjax").click(function() {
$("#bootstrapProgress").css("width", "0%");
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
type: "GET",
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
$("#bootstrapProgress").css("width", percentComplete + "%");
}
};
return xhr;
},
success: function() {
$("#bootstrapProgress").css("width", "100%");
}
});
});
A progress bar significantly enhances the user experience for AJAX requests. Choose the method that fits your framework and needs, whether it’s:
✔ Basic CSS Progress Bar
✔ jQuery UI Progress Bar
✔ Bootstrap Progress Bar
✔ File Upload Progress Bar
Would you like an example using React or Angular?