Leah Sapan
Leah Sapan

Reputation: 3791

Get the size of an AJAX response before it finishes loading

I'm using jQuery to load data via AJAX from a server, it's a fairly normal use case. The trick is that I'd like to get the expected content length from the request before it is completed; I want to be able to show a progress bar as the data is loaded.

Is there any way at all to do this? I have to imagine there is. Thanks!

Update: The server has to do quite a bit of work to generate the response, so I'd prefer not to hit it with two requests, it would defeat the purpose.

Upvotes: 0

Views: 2245

Answers (1)

Arindam Nayak
Arindam Nayak

Reputation: 7462

You can use xhr event in ajax call, and then hook up progress event to that, and check if event.lengthComputable= true, then you will get value, else you will not get value. You can check out following code.

$.ajax({
    type: 'POST',
    dataType: 'json',
    url: URL,
    cache: false,
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.responseText);
        alert(thrownError);
    },
    xhr: function () {
        var xhr = new window.XMLHttpRequest();
        //Download progress
        xhr.addEventListener("progress", function (evt) {
            console.log(evt.lengthComputable);
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                console.log(percentComplete );
            }
        }, false);
        return xhr;
    },
    beforeSend: function () {
      // before send
    },
    complete: function () {
       // complete.
    },
    success: function (json) {
       // success;
    }
});

Upvotes: 3

Related Questions