How do I catch the current percentage of a download?

Asked

Viewed 506 times

8

I want to get the value of the percentage of an ajax request on an external server. How to do?

$("#uptade_space_disk").click(function(){
     var url = "/calcular-espaco-em-disco"
     jQuery.ajax({
        url: url,
        dataType: 'script', 
        beforeSend: function() {
            $("#loader").show();
            $("#uptade_space_disk").hide();
        },                                      
        success: function() {
        },
        error: function() {
        }
    });
})

1 answer

5

What you are looking for is a progress event, which is updated as the download is processed. I have adapted your code based in that reply:

$("#uptade_space_disk").click(function(){
  var url = "/calcular-espaco-em-disco"
  $.ajax({
    url: url,
    dataType: 'script', 
    beforeSend: function () {
      $("#loader").show();
      $("#uptade_space_disk").hide();
    },                                      
    success: function () {},
    error: function () {},
    xhr: function () {
      // pega o objeto XmlHttpRequest que o jQuery está usando
      var xhr = $.ajaxSettings.xhr() ;
      // vincula a função ao evento
      xhr.onprogress = function(evt){
        $("#loader").text(Math.round(evt.loaded*100/evt.total) + '%');
      };
      // retorna o objeto para o jQuery
      return xhr;
    }
  });
});
  • Gustavo, you’ve got a problem there. I put console.log(Math.round(evt.Loaded*100/evt.total) + '%') and it only shows when it is 100% and has not updated #Loader.. what is?

  • 1

    Not every browser supports this event (in fact only today I learned that it exists). About update the #loader I gave a kick about how your code is organized, anything try to use .html().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.