Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a progress bar in jQuery.get()

is it possible to have a progress bar measuring the jQuery.get() progress?

like image 633
Omar Avatar asked Aug 31 '13 06:08

Omar


People also ask

How to show progress bar in ajax?

Use the ajaxStart to start your progress bar code. $(document). ajaxStop(function(){ // hide the progress bar $("#progressDialog"). modal('hide'); });


1 Answers

This is not given out-of-the-box in the current version of jQuery, but still possible with little effort.

You should listen to the progress event of the XMLHttpRequest which jQuery gives you access to. An example from Dave Bond's blog:

$.ajax(
{
  type: 'POST', // 'POST' here so that _upload_ progress _also_ makes sense; 
                // Change to 'GET' if you need. 
  url: "/", data: {}, 
  beforeSend: function(XMLHttpRequest)
  {
    //Upload progress
    XMLHttpRequest.upload.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {  
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
      }
    }, false); 

    //Download progress
    XMLHttpRequest.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {  
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
      }
    }, false); 
  },

  success: function(data){
    // successful completion handler
  }
});

Here the link to the docs on XMLHttpRequest's progress event.

You may also want to take a look a the jquery.ajax-progress plugin to avoid doing it yourself.


Notes:

  • Some older browsers may not support the progress event.

  • To calculate download progress, you must know the size of the resource to be downloaded, i.e. the server must send the Content-length HTTP header. If size is not known, then it's not possible to calculate the progress. This is what the lengthComputable property of the progress event is for.

like image 101
Alex Shesterov Avatar answered Sep 30 '22 01:09

Alex Shesterov