Abude
Abude

Reputation: 2162

How to make real progress bar of jQuery Ajax load request?

What I need is an animated progress bar (like the one on youtube) BUT please no plugins!

My ajax request looks like this:

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        //Download progress
        xhr.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                console.log(evt);
                var percentComplete = evt.loaded / evt.total * 100;
                //Do something with download progress
                // this is a static animation but i'm not able to make it work with the precentComplete that i have.
                $({
                    property: 0
                }).animate({
                    property: 105
                }, {
                    duration: 4000,
                    step: function() {
                        var _percent = Math.round(this.property);
                        $('#progress').css('width', _percent + "%");
                        if (_percent == 105) {
                            $("#progress").addClass("done");
                        }
                    },
                    complete: function() {
                        alert('complete');
                    }
                });
            }
        }, false);
        return xhr;
    },
    type: method,
    url: rest_api,
    headers: headers,
    timeout: 10000,
    dataType: 'json',
    data: http_content,
    beforeSend: function(xhr) {
        // do stuff
    },
    success: function(data, status, xhr) {
        // do stuff
    },
    error: function(xhr, e) {
        // do stuff
    }
});

So, I have an animation already made but I could not link it to be real, this is a static animation but I'm not able to make it work with the precentComplete that I have in the progress event.

Any ideas please? I need more clarification on this XHR2 with working snippet or example for better understanding.

The animation looks like this :jsFiddle

Upvotes: 3

Views: 6690

Answers (1)

lordvlad
lordvlad

Reputation: 5347

My first shot would be to define the progress bar outside the 'progress' event handler, and then only set the width property from within the event handler.

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        var progressBar = $("#progress");

        //Download progress
        xhr.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                console.log(evt);
                var percentComplete = /* compute it */;
                progressBar.style("width", percentComplete + "%");
            }
        }, false);
        return xhr;
    },
    ...
});

It seems not every browser allows you to track download progress that easy, you can find more info on how to actually calculate the progress here: AJAX Page Download progress

Upvotes: 2

Related Questions