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); } }); }); });
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 });
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!