Displaying a Progress Bar While Loading Data with AJAX
When performing an AJAX query that retrieves data from a database, it can take some time for the results to be returned. To provide feedback to the user during this loading process, a progress bar can be displayed.
Creating a Progress Bar with jQuery
The jQuery library offers built-in methods that facilitate the creation and manipulation of progress bars. To add a progress bar to your AJAX call, you can attach an event listener to the xhr object:
<code class="javascript">$.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); // Upload progress xhr.upload.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; // Update the progress bar here } }, false); // Download progress xhr.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; // Update the progress bar here } }, false); return xhr; }, type: 'POST', url: "/", data: {}, success: function(data) { // Hide the progress bar and display the results } });</code>
In this code:
By implementing this approach, you can enhance your AJAX callbacks with a user-friendly progress bar, providing visual feedback during data loading operations.
The above is the detailed content of How to Display a Progress Bar During AJAX Data Loading with jQuery?. For more information, please follow other related articles on the PHP Chinese website!