1

I have this code

for(var i=0; i<ObjectMover.length; i++)
{
    var formdata = new FormData();
    formdata.append("fl", ObjectMover[i]);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", function(ev) 
    {
        if(ev.lengthComputable) 
        {
             $('#pb'+i).css('width', (ev.loaded / ev.total) * 100 + "%");
        }
    }, false);
    ajax.open("POST", "file_upload.php");
    ajax.send(formdata);
}

this code is working fine but the problem is that when I upload multiple files say 3 files then it shows only the progress of 3rd upload. While it is uploading all files to the server but shows the progress of only last file. I checked by putting console.log(i); in progress event like

    ajax.upload.addEventListener("progress", function(ev) 
    {
        if(ev.lengthComputable) 
        { 
                         console.log(i);
             $('#pb'+i).css('width', (ev.loaded / ev.total) * 100 + "%");
        }
    }, false);

Console shows only last file number (3). Why? Where am I making mistake. While I have same code in other file and that works good with same as above code. With my above code, there becomes 3 progress bars for each file individually but only last (3rd) progress bar shows progress of 3rd file. I checked all my "error", "load", "progress" and "abort" events if there was error from any of them but not at all. Even all upload requests are giving message on "load" event.

  • Similiar http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Musa Feb 06 '14 at 19:52
  • I didn't know that it is the problem of Loop so I couldn't find this. I thought it would be just Ajax problem. Anyway thanks –  Feb 06 '14 at 20:32

1 Answers1

0

Problem

That's simple because in your code

  $('#pb'+i).css('width', (ev.loaded / ev.total) * 100 + "%");

i is set to the length of your total files as of your for loop and therefore it simply give width to your i progress bar and that's last one no matter which progress event is responsing.

Solution

instead of sending files from a single loop send your files from another loop calling your upload function from that loop giving your file as parameter in it. Something similar to this

function UploadMyFilesQueue()
{
    for(var i=0; i<files.length; i++)
    {
          UploadThisFile(files[i], i);
    }
}

function UploadThisFile(file, pbid)
{
    var formdata = new FormData(); 
    formdata.append("fl", file);
    var ajax = new XMLHttpRequest();
    ajax.send(formdata);
}
Airy
  • 5,484
  • 7
  • 53
  • 78
  • Thanks Abdul Jabbar WebBestow. It solved. I couldn't understand the problem. Nice catch. –  Feb 06 '14 at 20:33