"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Display a Progress Bar During AJAX Data Loading with jQuery?

How to Display a Progress Bar During AJAX Data Loading with jQuery?

Published on 2024-11-09
Browse:189

How to Display a Progress Bar During AJAX Data Loading with jQuery?

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:

$.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
    }
});

In this code:

  • The progress event listener for the upload property tracks the progress of sending data to the server.
  • The progress event listener for the xhr object tracks the progress of receiving data from the server.
  • You can use the percentComplete variable to determine the completion percentage and update the progress bar accordingly.
  • After the data has been successfully retrieved and processed, the progress bar can be hidden and the results can be displayed.

By implementing this approach, you can enhance your AJAX callbacks with a user-friendly progress bar, providing visual feedback during data loading operations.

Release Statement This article is reprinted at: 1729694481 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3