How to Use jQuery to Add a Progress Bar to Ajax-Loaded Content?

DDD
Release: 2024-10-24 06:10:30
Original
670 people have browsed it

How to Use jQuery to Add a Progress Bar to Ajax-Loaded Content?

Show Progress Bar During Ajax-Loaded Content

In web development, it's often desirable to display a progress bar while data is retrieved and loaded into a page via Ajax. This helps provide visual feedback to users, indicating that the process is ongoing.

Ajax Code Example:

Let's consider an example where you have a dropdown box that triggers an Ajax query upon selection, retrieving data from a database:

<code class="javascript">$("#client").on("change", function() {
  var clientid = $("#client").val();

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

Adding a Progress Bar Using jQuery:

To add a progress bar to this Ajax operation, you can utilize the xhr() method within the $.ajax() configuration:

<code class="javascript">$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();

    // Upload progress listener
    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        // Update progress bar accordingly
      }
    });

    // Download progress listener
    xhr.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        // Update progress bar accordingly
      }
    });

    return xhr;
  },
  type: 'POST',
  url: &quot;/&quot;,
  data: {},
  success: function(data){
        // Do something success-ish
  }
});</code>
Copy after login

This code creates an XMLHttpRequest object and adds event listeners for both upload and download progress. As the data is transferred, the percentComplete variable will provide a value that you can use to update the progress bar on your web page.

The above is the detailed content of How to Use jQuery to Add a Progress Bar to Ajax-Loaded Content?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!