Thursday, September 10, 2015

What is the cleanest way to get the progress of JQuery ajax request?

Something like this for $.ajax (HTML5 only though):

$.ajax({
        type: 'POST',
        url: "/",
        data: {},
        dataType: 'json',
        xhr: function() {
            $('#formLoadingDiv').show();

            var xhr = new window.XMLHttpRequest();

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

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

            return xhr;
        },
    })
    .done(function(data) {
        if (data.status === true) {} else if ('errors' in data) {
            console.log(data);
        }
    })
    .fail(function() {
        console.log('failed');
    })
    .always(function() {
        $('#formLoadingDiv').hide();
    });

Reference:

http://stackoverflow.com/questions/19126994/what-is-the-cleanest-way-to-get-the-progress-of-jquery-ajax-request

No comments: