Search code examples
javascriptjqueryajaxprogress

Multiple progress status + Ajax form plugin


I'm using Ajax Form plugin, And I had a loop for send multiple requests. I'm trying to get the individual progress of each file. Seems that works, but the progress of the files only show in the last <p> of the code.

for (var i = 0; i < inp.files.length; i++) {
$('form').ajaxSubmit({
beforeSend: function() {
    $('body').append('<p class="c'+ i +'"></p>'); 
    var classe = '.c' + i;
},
uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';

    $(classe).append(percentVal);
    //console.log(percentVal, position, total);
}
});
}

The HTML output for 2 files:

<p class="c0"/>
<p class="c1">
79%
100%
81%
100%
</p>

There's two 100% that seems that it get the progress of the two files. But, it just print in the last element. Thanks


Solution

  • because classe change to c1 before the response from c0 come in... Put it into a anonym function.

    for (var i = 0; i < inp.files.length; i++) {
        (function () {
            var classe = '.c' + i;
            $('form').ajaxSubmit({
                beforeSend: function () {
                    $('body').append('<p class="c' + i + '"></p>');
                },
                uploadProgress: function (event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
    
                    $(classe).append(percentVal);
                    //console.log(percentVal, position, total);
                }
            });
        }());
    }
    

    (NOT TESTED)

    Or you have to change the Ajax request to sync