How to Display Progress Bar During Ajax Loading?

DDD
Release: 2024-10-24 07:30:29
Original
642 people have browsed it

How to Display Progress Bar During Ajax Loading?

Displaying Progress Bar During Ajax Loading

When performing data retrieval using Ajax, you may encounter a delay while waiting for the server response. To improve user experience, you can display a progress bar to indicate the loading status. This article will guide you through showing a progress bar using Ajax.

Ajax Code:

The provided Ajax code uses jQuery to handle client-side data retrieval and display results.

$(function() {
    $("#client").on("change", function() {
      var clientid=$("#client").val();

        $.ajax({
            type:"post",
            url:"clientnetworkpricelist/yourfile.php",
            data:"title="+clientid,
            success:function(data){
             $("#result").html(data);
            }
        });

    });
});
Copy after login

Adding Progress Event Listener:

To add a progress event listener to the Ajax request, use the xhr option as follows:

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();

        // Upload progress event listener
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                // Calculate upload progress percentage
                var percentComplete = evt.loaded / evt.total;
                // Update progress bar (example: display the percentage)
                console.log(percentComplete);
            }
        });

        // Download progress event listener
        xhr.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                // Calculate download progress percentage
                var percentComplete = evt.loaded / evt.total;
                // Update progress bar (example: display the percentage)
                console.log(percentComplete);
            }
        });

        return xhr;
    },
    // Rest of the Ajax options remain the same
});
Copy after login

This code registers event listeners for both upload and download progress events, allowing you to track the progress and update the progress bar accordingly.

The above is the detailed content of How to Display Progress Bar During Ajax Loading?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template