Search code examples
javascriptjqueryfor-loopjquery-forms-plugin

JavaScript for loop prevent continuing until upload complete


To upload multiple files, I am using JavaScript to loop through the files. To upload the files I am using the jQuery form plugin http://archive.plugins.jquery.com/project/form

Now, when the loop runs through, it runs to the end of the loop instantly, and uploads all files in one go.

Is there a way to get the loop to hold off during each upload?

This is an example of the loop im using (the actual code is quite large)

for(i=0;i<=num;i++)
{
    if(go1){
        <?php //if 1 upload only, hide add and upload button ?>
        $('#ad,#ok').hide();
        var z=i;
        $('#up'+i).ajaxSubmit({
            dataType:"json",
            beforeSubmit:function(before){
                $('#loadingsignup').show;
                $("#resultsignup").empty().hide();
            },
            success:function(retour){
                res=retour;
                if(num<1){  <?php // only one upload, redirect if uploaded correct, reintroduce upload button if error ?>
                    if(res.ok=="ok"){
                        window.location.replace('<?php echo $config['baseurl']; ?>/player/'+res.aid);
                    }else{
                        $('#rs'+z).append('<div class="pasgood">'+res.err+'</div>').show();
                        $('#ad,#ok').show();
                    }
                }
            }
        }); 

    }
}

I really need the loop to move through the uploads one at a time.


Solution

  • No, the loop is synchronous while the upload is asynchronous. If you want the uploads to happen one after the other, you will need to fire the second one from the success callback of the first one etc.

    function upload(i, suc, err) {
        if (i > num)
            return suc();
        $('#up'+i).ajaxSubmit({
            dataType:"json",
            beforeSubmit:function(before){
                $('#loadingsignup').show();
                $("#resultsignup").empty().hide();
            },
            success:function(res){
                if(res.ok=="ok"){
                    $('#ad,#ok').show();
                    upload(i+1, suc, err); // next one
                } else {
                    $('#rs'+i).append('<div class="pasgood">'+res.err+'</div>').show();
                    err(res.err); // or continue with the rest?
                }
            },
            error: err
        });
    }
    upload(0, function allDone(){
        window.location.replace('<?php echo $config['baseurl']; ?>/player/');
    }, function somethingWrong(){ … });